pyccapt.calibration.core package

Submodules

pyccapt.calibration.core.calibration module

pyccapt.calibration.core.calibration.auto_detect_reference_peaks(calibration_array, n_peaks=6, prominence=100, distance=500, hist_bin_size=0.1, event_mask=None)[source]

Public helper for stable multi-peak evaluation windows used by auto calibration.

event_mask (optional) is a boolean array the same length as calibration_array: True keeps the ion, False ignores it. Use this to detect peaks on calibration-trustworthy ions only (single-hit / excluded-correlations subsets from pyccapt.calibration.core.event_filters). Default None preserves legacy behavior.

pyccapt.calibration.core.calibration.bowl_correction(dld_x_bowl, dld_y_bowl, dld_t_bowl, variables, det_diam, maximum_location, sample_range_max, sample_size, calibration_mode, fit_mode, index_fig, plot, save, fig_size=(7, 5), bin_size=0.01, sampling_mode='polar')[source]

Perform bowl correction on the input data.

Parameters:
  • dld_x_bowl (numpy.ndarray) – X coordinates of the data points.

  • dld_y_bowl (numpy.ndarray) – Y coordinates of the data points.

  • dld_t_bowl (numpy.ndarray) – Time values of the data points.

  • det_diam (float) – Diameter of the detector.

  • maximum_location (float) – Maximum location for normalization.

  • sample_range_max (str, optional) – Sample range maximum (‘mean’ or ‘histogram’).

  • sample_size (int) – Size of each rectangle in mm.

  • calibration_mode (str) – Calibration mode (‘tof’ or ‘mc’).

  • fit_mode (str) – Fit mode (‘curve_fit’ or ‘hemisphere_fit’).

  • index_fig (int) – Index for figure naming.

  • plot (bool) – Flag indicating whether to plot the surface.

  • save (bool) – Flag indicating whether to save the plot.

  • fig_size (tuple) – Size of the figure.

  • bin_size (float) – Size of the bin.

Returns:

Optimized parameters of the bowl correction.

Return type:

parameters (numpy.ndarray)

pyccapt.calibration.core.calibration.bowl_correction_main(dld_x, dld_y, dld_highVoltage, variables, det_diam, sample_size, fit_mode, calibration_mode, index_fig, plot, save, maximum_cal_method='mean', maximum_sample_method='mean', fig_size=(5, 5), fast_calibration=False, bin_size=0.01, peak_maximum=0, calibration_apply=True, sampling_mode='polar', refine_nelder_mead=False)[source]

Perform bowl correction on the input data and plot the results.

Parameters:
  • dld_x (numpy.ndarray) – X positions.

  • dld_y (numpy.ndarray) – Y positions.

  • dld_highVoltage (numpy.ndarray) – High voltage values.

  • det_diam (float) – Detector diameter.

  • sample_size (int) – Sample size.

  • fit_mode (str) – Fit mode (‘curve_fit’, ‘ml_fit’, or ‘robust_fit’).

  • calibration_mode (str) – Calibration mode (‘tof’ or ‘mc’).

  • index_fig (int) – Index figure.

  • plot (bool) – Flag indicating whether to plot the results.

  • save (bool) – Flag indicating whether to save the plots.

  • maximum_cal_method (str, optional) – Maximum calculation method (‘mean’ or ‘histogram’).

  • maximum_sample_method (str, optional) – Sample range maximum (‘mean’ or ‘histogram’).

  • fig_size (tuple, optional) – Figure size.

  • fast_calibration (bool, optional) – Flag indicating whether to perform fast calibration.

  • bin_size (float, optional) – Size of the bin.

Returns:

None

pyccapt.calibration.core.calibration.joint_voltage_bowl_corr_main(dld_x, dld_y, dld_highVoltage, variables, det_diam, calibration_mode='mc', sample_size=9, bin_size=0.01, n_peaks=4, prominence=100, distance=500, sampling_mode='polar')[source]

Fit a smooth combined voltage-plus-detector correction surface from several peaks.

pyccapt.calibration.core.calibration.multi_peak_bowl_corr_main(dld_x, dld_y, dld_highVoltage, variables, det_diam, calibration_mode='mc', fit_mode='robust_fit', sample_size=9, bin_size=0.01, n_peaks=3, prominence=100, distance=500, sampling_mode='polar')[source]

Bowl correction using multiple auto-detected peaks simultaneously.

pyccapt.calibration.core.calibration.multi_peak_voltage_corr_main(dld_highVoltage, variables, calibration_mode='mc', model='robust_fit', bin_size=0.01, n_peaks=3, prominence=100, distance=500)[source]

Voltage correction using multiple auto-detected peaks simultaneously.

pyccapt.calibration.core.calibration.recompute_peak_window(variables, calibration_mode: str = 'mc', *, prominence: float = 100, distance: int = 10, hist_bin_size: float = 0.05, lim=None, window_inflate: float = 2.0, target_position=None) tuple[source]

Lightweight peak-window recompute. NO Matplotlib.

Detects peaks via auto_detect_reference_peaks on the currently calibrated array and updates variables.selected_x1/x2 to the dominant peak (or, if target_position is set, the peak closest to that mass).

This is the headless equivalent of mc_plot.hist_plot(..., plot_show=False) for use inside auto-calibration loops where the Matplotlib stack adds significant per-iteration overhead.

Parameters:
  • variables (Variables) – Calibration state container.

  • calibration_mode ({'mc', 'tof'})

  • prominence (passed to peak detection.)

  • distance (passed to peak detection.)

  • hist_bin_size (passed to peak detection.)

  • lim (float, optional) – Upper limit on values considered. Defaults to variables.max_tof for ‘tof’ and 400.0 for ‘mc’.

  • window_inflate (float) – Multiplier on the FWHM-based window width. 2.0 keeps the window wide enough for stable MRP scoring on tight peaks.

  • target_position (float, optional) – If supplied, pick the peak nearest this m/c instead of the most prominent one. Useful for keeping the same physical peak window across calibration iterations as the peak drifts.

Returns:

(x1, x2, position)

Return type:

tuple of floats

pyccapt.calibration.core.calibration.voltage_corr_main(dld_highVoltage, variables, sample_size, mode, calibration_mode, index_fig, plot, save, maximum_cal_method='mean', maximum_sample_method='mean', fig_size=(5, 5), fast_calibration=False, bin_size=0.01, model='curve_fit', peak_maximum=0, calibration_apply=True, refine_nelder_mead=False)[source]

Perform voltage correction on the given data.

Parameters:
  • dld_highVoltage (numpy.ndarray) – Array of high voltages.

  • sample_size (int) – Size of the sample.

  • mode (str) – Mode of the correction.

  • calibration_mode (str) – Calibration mode (‘tof’ or ‘mc’).

  • index_fig (int) – Index of the figure.

  • plot (bool) – Whether to plot the results.

  • save (bool) – Whether to save the plots.

  • noise_remove (bool, optional) – Whether to remove noise. Defaults to True.

  • maximum_cal_method (str, optional) – Maximum calculation method (‘mean’, ‘histogram’, ‘median’).

  • maximum_sample_method (str, optional) – Sample range maximum (‘mean’, ‘histogram’, ‘median’).

  • fig_size (tuple, optional) – Size of the figure. Defaults to (5, 5).

  • fast_calibration (bool, optional) – Whether to perform fast calibration. Defaults to False.

  • bin_size (float, optional) – Size of the bin. Defaults to 0.01.

pyccapt.calibration.core.calibration.voltage_correction(dld_highVoltage_peak, dld_t_peak, variables, maximum_location, index_fig, figname, sample_size, mode, calibration_mode, sample_range_max, bin_size, plot=True, save=False, fig_size=(5, 5), model='curve_fit')[source]

Performs voltage correction and plots the graph based on the passed arguments.

Parameters: - dld_highVoltage_peak (array): Array of high voltage peaks. - dld_t_peak (array): Array of t peaks. - maximum_location (float): Maximum location value. - index_fig (string): Index of the saved plot. - figname (string): Name of the saved plot image. - sample_size (string): Sample size. - mode (string): Mode (‘ion_seq’/’voltage’). - calibration_mode (string): Type of calibration mode (tof/mc). - sample_range_max (string): Type of peak_x mode (histogram/mean/median). - outlier_remove (bool): Indicates whether to remove outliers. Default is True. - plot (bool): Indicates whether to plot the graph. Default is True. - save (bool): Indicates whether to save the plot. Default is False. - fig_size (tuple): Figure size in inches. Default is (7, 5). - model (string): Type of model (‘curve_fit’/’robust_fit’). Default is ‘curve_fit’. - bin_size (float): Size of the bin.

Returns: - fitresult (array): Corrected voltage array.

pyccapt.calibration.core.gui_ion_select module

class pyccapt.calibration.core.gui_ion_select.MyWindow(*args: Any, **kwargs: Any)[source]

Bases: QMainWindow

deselectAllRowsAndColumns()[source]
initUI()[source]
onSelectionChanged()[source]
sortByColumn(column)[source]

pyccapt.calibration.core.hist_bin_optimizer module

pyccapt.calibration.core.hist_bin_optimizer.bin_width_optimizer_1d(data, plot=False)[source]

Calculates the optimal bin width for a 1-dimensional histogram.

Parameters:
  • data (array-like) – Input data for which the histogram is calculated.

  • plot (bool, optional) – If True, a histogram plot will be displayed. Defaults to False.

Returns:

A tuple containing the optimal bin number and bin width.

Return type:

tuple

pyccapt.calibration.core.hist_bin_optimizer.bin_width_optimizer_2d(x, y, plot=False)[source]

Calculates the optimal bin width for a 2-dimensional histogram.

Parameters:
  • x (array-like) – Input data for the x-axis.

  • y (array-like) – Input data for the y-axis.

  • plot (bool, optional) – If True, a 2D histogram plot will be displayed. Defaults to False.

Returns:

A tuple containing the optimal bin number for x and y axes.

Return type:

tuple

pyccapt.calibration.core.interactive_point_identification module

Interactive peak annotation helpers for matplotlib plots.

class pyccapt.calibration.core.interactive_point_identification.AnnotationFinder(xdata, ydata, annotations, variables, ax=None, xtol=None, ytol=None)[source]

Bases: object

Matplotlib callback that selects and deselects nearest annotated peaks.

Left click selects the nearest point within tolerance. Right click deselects it.

annotate_plotter(event) None[source]

Handle matplotlib click events and update selected annotations.

annotates_plotter(event) None[source]

Backward-compatible wrapper for legacy method name.

deselectPoint(ax, x, y, annotation) None[source]

Backward-compatible wrapper for legacy method name.

deselect_point(ax, x, y, annotation) None[source]

Hide one annotation and remove it from shared state if present.

drawAnnote(ax, x, y, annotation) None[source]

Backward-compatible wrapper for legacy method name.

drawSpecificAnnote(annotation) None[source]

Backward-compatible wrapper for legacy method name.

draw_annotation(ax, x, y, annotation) None[source]

Draw one annotation and register it in shared state.

draw_specific_annotation(annotation) None[source]

Draw annotation for every matching point label.

class pyccapt.calibration.core.interactive_point_identification.AnnoteFinder(xdata, ydata, annotations, variables, ax=None, xtol=None, ytol=None)[source]

Bases: AnnotationFinder

Backward-compatible class alias with legacy name.

pyccapt.calibration.core.interactive_point_identification.distance(x1: float, x2: float, y1: float, y2: float) float[source]

Return Euclidean distance between two 2D points.

pyccapt.calibration.core.interactive_point_identification.distances(x1: float, x2: float, y1: float, y2: float) float[source]

Backward-compatible alias for distance().

pyccapt.calibration.core.ion_selection module

pyccapt.calibration.core.ion_selection.chunks(lst, n)[source]

Yield successive n-sized chunks from a list.

Parameters:
  • lst (list) – The input list.

  • n (int) – The chunk size.

Yields:

list – Successive n-sized chunks from the input list.

pyccapt.calibration.core.ion_selection.create_formula_latex(aa, num_charge=0)[source]

Create a LaTeX representation of a chemical formula.

Parameters:
  • aa (str) – The chemical formula.

  • num_charge (int) – The number of charges associated with the formula.

Returns:

The LaTeX representation of the chemical formula.

Return type:

str

pyccapt.calibration.core.ion_selection.display_color(color)[source]

This function is used to display the color in the table

Arg:

color (str): The color in hex format

Returns:

str: The color in hex format

pyccapt.calibration.core.ion_selection.find_closest_elements(target_elem, num_elements, abundance_threshold=0.0, charge=4, variables=None)[source]

Find the closest elements to a target element.

Parameters:
  • target_elem (float) – Target element.

  • num_elements (int) – Number of closest elements to find.

  • abundance_threshold (float) – Abundance threshold for filtering elements (as a percentage).

  • charge (int) – Charge value.

  • variables (object) – Object containing the variables.

Returns:

DataFrame containing closest elements and their properties.

Return type:

pd.DataFrame

pyccapt.calibration.core.ion_selection.fix_parentheses(c)[source]

Fix parentheses in a given string by expanding the elements inside them.

Parameters:

c (str) – Input string containing parentheses.

Returns:

String with expanded elements inside parentheses.

Return type:

str

pyccapt.calibration.core.ion_selection.load_elements(target_elements, abundance_threshold=0.0, charge=4, variables=None)[source]

create a dataframe from the given list of ions.

Parameters:
  • target_elements (str) – Target elements.

  • abundance_threshold (float) – Abundance threshold for filtering elements (as a percentage).

  • charge (int) – Charge value.

  • data_table (str) – Path to the data table (HDF5 file).

  • variables (object) – Object containing the variables.

Returns:

DataFrame containing closest elements and their properties.

Return type:

pd.DataFrame

pyccapt.calibration.core.ion_selection.molecule_create(element_list, max_complexity, charge, abundance_threshold, variables=None, latex=True)[source]

Generate a list of isotopes for a given target element.

Parameters:
  • element_list (str) – The target element to find isotopes for.

  • max_complexity (int) – The maximum complexity of the molecule.

  • charge (int) – The charge of the target element.

  • abundance_threshold (float) – The abundance threshold for filtering isotopes.

  • variables (object, optional) – The variables object. Defaults to None.

  • latex (bool, optional) – Whether to generate LaTeX representation of formulas. Defaults to True.

Returns:

A DataFrame containing the list of isotopes with their weights and abundances.

Return type:

pd.DataFrame

pyccapt.calibration.core.ion_selection.molecule_manual(target_element, charge, latex=True, variables=None)[source]

Generate a list of isotopes for a given target element.

Parameters:
  • target_element (str) – The target element to find isotopes for.

  • charge (int) – The charge of the target element.

  • latex (bool, optional) – Whether to generate LaTeX representation of formulas. Defaults to True.

  • variables (object, optional) – The variables object. Defaults to None.

Returns:

A DataFrame containing the list of isotopes with their weights and abundances.

Return type:

pd.DataFrame

pyccapt.calibration.core.ion_selection.ranging_dataset_create(variables, row_index, mass_ion)[source]

This function is used to create the ranging dataset

Arg:

variables (class): The class of the variables row_index (int): The index of the selected row mass_ion (float): The mass of the element

Returns:

None

pyccapt.calibration.core.ion_selection.rank_candidate_assignments(df, target_mass=None, variables=None)[source]

Rank candidate atoms/molecules using mass error, abundance, and simplicity.

Lower score is better. The resulting dataframe is deduplicated and sorted so the most plausible assignment appears first.

pyccapt.calibration.core.ion_selection.transform_combination_and_isotopes(combination, isotopes)[source]

Transform the combination and isotopes lists to remove duplicates.

Parameters:
  • combination (list) – The list of elements.

  • isotopes (list) – The list of isotopes.

Returns:

The new combination list.

Return type:

list

pyccapt.calibration.core.logging_library module

pyccapt.calibration.core.logging_library.add_file_handler(log_creator, formatter, file_handler)[source]

Add a file handler to the logger.

This function allows the respective module to add a file handler to the logger.

Parameters:
  • log_creator (logging.Logger) – The logger object to which the file handler is added.

  • formatter (logging.Formatter) – The type of logging format.

  • file_handler (dict) – The module specification of the file handler.

Returns:

The modified logger object with the additional file handler.

Return type:

logging.Logger

pyccapt.calibration.core.logging_library.logger_creator(script_name, file_handler=None)[source]

Instantiate and configure a logger object for logging.

The function uses the native logging library in Python.

Parameters:
  • script_name (str) – The name of the script or module using the logger.

  • file_handler (dict, optional) – Specification of the file handler. Defaults to None.

Returns:

The logger object that can be used to log statements of different levels:
  • INFO: Useful information.

  • WARNING: Something is not right.

  • DEBUG: A debug message.

  • ERROR: A major error has occurred.

  • CRITICAL: A fatal error. Cannot continue.

Return type:

logging.Logger

pyccapt.calibration.core.mc_plot module

class pyccapt.calibration.core.mc_plot.AptHistPlotter(mc_tof, variables=None)[source]

Bases: object

This class plots the histogram of the mass-to-charge ratio (mc) or time of flight (tof) data.

Initializes all the attributes of AptHistPlotter.

Parameters:
adjust_labels()[source]

Adjust the labels.

Parameters:

None

Returns:

None

calculate_noise(fig_size=(9, 5), plot_without_noise=False)[source]

Calculate noise after fitted background subtraction.

change_peak_color(peak_loc, dx, color='red')[source]

Change the color of the peak.

Parameters:
  • peak_loc (float) – The location of the peak.

  • dx (float) – The width of the peak.

  • color (str) – The color of the peak.

Returns:

None

draw_rectangle(initial=False)[source]

Draw auto-selected peak rectangle.

exponential_decay_with_linear_and_dc(x, a, b, c, d)[source]

Exponential decay helper retained for compatibility.

find_peaks_and_widths(prominence=None, distance=None, percent=50)[source]

Find peaks and widths and update shared variables.

manual_background_fit()[source]

Interactive manual background fitting.

mrp_calculation()[source]

Calculate MRP metrics for current histogram peaks.

plot_background(mode, non_peaks=None, lam=1000000.0, tol=0.1, max_iter=100, num_std=3.0, plot=True, patch=True)[source]

Fit and plot histogram background.

plot_color_legend(loc, detailed_isotope=False, detailed_charge=False)[source]

Plot the color legend.

Parameters:

loc (str) – The location of the legend.

Returns:

None

plot_founded_range_loc(df, remove_lines=False)[source]

Plot the founded range location.

Parameters:
  • df (data frame) – The data frame of the founded range.

  • remove_lines (bool) – Whether to remove the lines.

Returns:

None

plot_hist_info_legend(label='mc', mrp_all=False, background=None, legend_mode='long', loc='left')[source]

Plot summary legend info for histogram quality metrics.

plot_histogram(bin_width=0.1, normalize=False, label='mc', log=True, grid=False, steps='stepfilled', fig_size=(9, 5), plot_show=True, fast=False)[source]

Plot the histogram of the mc or tof data.

Parameters:
  • bin_width (float) – The width of the bins.

  • normalize (bool) – Whether to normalize the histogram.

  • label (str) – The label of the x-axis (‘mc’ or ‘tof’).

  • log (bool) – Whether to use log scale for the y-axis.

  • grid (bool) – Whether to show the grid.

  • steps (str) – The type of the histogram (‘stepfilled’ or ‘bar’).

  • fig_size (tuple) – The size of the figure.

  • plot_show (bool) – Whether to show the plot.

  • fast (bool) – Use np.histogram + fill_between instead of ax.hist for speed.

Returns:

A tuple of the y and x values of the histogram.

Return type:

tuple

plot_horizontal_lines()[source]

Plot the horizontal lines.

Parameters:

None

Returns:

None

plot_line_hist()[source]

Plot the histogram as a line plot.

Parameters:

None

Returns:

None

plot_peaks(range_data=None, mode='peaks')[source]

Plot the peaks of the histogram.

Parameters:
  • range_data (data frame) – The range data.

  • mode (str) – The mode of the peaks (‘peaks’, ‘range’, or ‘peaks_range’).

Returns:

None

plot_range(range_data, legend=True, legend_loc='upper right')[source]

Plot the range of the histogram.

Parameters:
  • range_data (data frame) – The range data.

  • legend (bool) – Whether to show the legend.

  • legend_loc (str) – The location of the legend.

Returns:

None

save_fig(label, fig_name)[source]

Save the figure.

Parameters:
  • label (str) – The label of the x-axis (‘mc’ or ‘tof’).

  • fig_name (str) – The name of the figure.

Returns:

None

selector(selector='rect')[source]

Attach interaction selector handlers.

zoom_to_x_range(x_min, x_max, reset=False)[source]

Zoom the histogram to a selected x-range or reset view.

pyccapt.calibration.core.mc_plot.hist_plot(variables, bin_size, log, target, normalize, prominence, distance, percent, selector, figname, lim, peaks_find=True, peaks_find_plot=False, plot_ranged_peak=False, plot_ranged_colors=False, mrp_all=False, background=None, grid=False, ranging_mode=False, range_sequence=[], range_mc=[], range_detx=[], range_dety=[], range_x=[], range_y=[], range_z=[], range_vol=[], save_fig=True, print_info=True, legend_mode='long', draw_calib_rect=False, figure_size=(9, 5), plot_show=True, fast_calibration=False, fast_histogram=True, initial_peak_selection=False, compute_mrp=True)[source]

Backward-compatible wrapper delegating to mc_plot_api.

pyccapt.calibration.core.share_variables module

class pyccapt.calibration.core.share_variables.SharedVariablesBase[source]

Bases: object

Shared state helpers used by calibration and visualization workflows.

build_calibration_mask(calibration_mode: str) ndarray[source]

Build a boolean mask from the selected peak range and calibration mode.

clear_calibration_peak_range(calibration_mode: str | None = None) None[source]

Clear one or all stored calibration-only peak windows.

clear_calibration_selection_mask(calibration_mode: str | None = None) None[source]

Clear one or all locked calibration ion masks.

clear_peak_range() None[source]

Reset selected peak window to an unselected state.

ensure_valid_peak_range() None[source]

Validate that a peak range is selected and logically valid.

get_calibration_array(calibration_mode: str) ndarray[source]

Return the selected calibrated array for a calibration mode.

get_calibration_peak_range(calibration_mode: str) tuple[float, float][source]

Return the active peak window for calibration, preferring the stored snapshot.

resolve_result_data_file(filename: str) str[source]

Resolve filename inside result_data_path.

resolve_result_file(filename: str) str[source]

Resolve filename inside result_path.

restore_data_from_backup() DataFrame[source]

Restore the original dataframe snapshot and resynchronize shared arrays.

set_calibration_peak_range(calibration_mode: str, left: float, right: float) tuple[float, float][source]

Store a calibration-only copy of the active peak window for one mode.

set_calibration_selection_mask(calibration_mode: str, mask: ndarray) None[source]

Lock a boolean ion-selection mask for repeated calibration steps.

set_peak_range(left: float, right: float) None[source]

Set selected peak window after validating numeric order.

set_result_data_directory(directory: str | Path) str[source]

Set and return the normalized directory used for data exports.

set_result_directory(directory: str | Path) str[source]

Set and return the normalized directory used for figures and plots.

sync_from_data(data: DataFrame | None = None, *, update_backups: bool = False, clear_selection: bool = True) DataFrame[source]

Synchronize shared arrays from the current dataframe after crop/load/reset operations.

class pyccapt.calibration.core.share_variables.Variables[source]

Bases: SharedVariablesBase

Container for shared variables across calibration workflows.

property data_name

Backward-compatible alias for dataset_name.

property dld_highVoltage

Backward-compatible alias for legacy camelCase field names.

pyccapt.calibration.core.share_variables.get_project_path() str[source]

Return the project root path by walking parents until setup.py is found.

pyccapt.calibration.core.tools module

pyccapt.calibration.core.tools.hist_plot(mc_tof, variables, bin, label, range_data=None, adjust_label=False, ranging=False, hist_color_range=False, log=True, mode='count', percent=50, peaks_find=True, peaks_find_plot=False, plot=False, prominence=50, distance=None, h_line=False, selector='None', fast_hist=True, fig_name=None, text_loc='right', fig_size=(9, 5), background={'calculation': False})[source]

Generate a histogram plot with optional peak_x finding and background calculation.

Parameters:
  • mc_tof (array-like) – Input array of time-of-flight values.

  • bin (float) – Bin width for the histogram.

  • label (str) – Label type (‘mc’ or ‘tof’).

  • range_data (optional, array-like) – Range data.

  • adjust_label (bool) – Flag to adjust overlapping peak_x labels.

  • ranging (bool) – Flag to enable ranging.

  • hist_color_range (bool) – Flag to enable histogram color ranging.

  • log (bool) – Flag to enable logarithmic y-axis scale.

  • mode (str) – Mode for histogram calculation (‘count’ or ‘normalised’).

  • percent (int) – Percentage value for peak_x width calculation.

  • peaks_find (bool) – Flag to enable peak_x finding.

  • peaks_find_plot (bool) – Flag to plot peak_x finding results.

  • plot (bool) – Flag to enable plotting.

  • prominence (float) – Minimum prominence value for peak_x finding.

  • distance (optional, float) – Minimum horizontal distance between peaks for peak_x finding.

  • h_line (bool) – Flag to draw horizontal lines for peak_x width.

  • selector (str) – Selector mode for interactive selection (‘None’, ‘rect’, or ‘peak_x’).

  • fast_hist (bool) – Flag to enable fast histogram calculation.

  • fig_name (optional, str) – Name of the figure file to save.

  • text_loc (str) – Location of the text annotation (‘left’ or ‘right’).

  • fig_size (tuple) – Size of the figure.

  • background (dict) – Background calculation options.

Returns:

Tuple containing x_peaks, y_peaks, peaks_widths, and mask.

Return type:

tuple

Raises:

ValueError – If an invalid mode or selector is provided.

pyccapt.calibration.core.tools.mc_hist_plot(variables, bin_size, mode, prominence, distance, percent, selector, plot, figname, lim, peaks_find_plot)[source]

Plot the mass spectrum or tof spectrum. It is helper function for tutorials. :param variables: Variables object. :type variables: object :param bin_size: Bin size for the histogram. :type bin_size: float :param mode: ‘mc’ for mass spectrum or ‘tof’ for tof spectrum. :type mode: str :param prominence: Prominence for the peak_x finding. :type prominence: float :param distance: Distance for the peak_x finding. :type distance: float :param percent: Percent for the peak_x finding. :type percent: float :param selector: Selector for the peak_x finding. :type selector: str :param plot: Plot the histogram. :type plot: bool :param figname: Figure name. :type figname: str :param lim: Limit for the histogram. :type lim: float :param peaks_find_plot: Plot the peaks. :type peaks_find_plot: bool

Returns:

None

pyccapt.calibration.core.widgets module

pyccapt.calibration.core.widgets.buttonWidget(buttonText)[source]

Create a button widget.

Parameters:

buttonText (str) – Text to be displayed on the button.

Returns:

Button widget object.

Return type:

button (object)

pyccapt.calibration.core.widgets.compute_element_isotope_values_according_to_selected_charge(mode='calibration')[source]

Compute the element and isotope values based on the selected charge.

Parameters:

mode (str) – Computation mode. Defaults to ‘calibration’.

pyccapt.calibration.core.widgets.dataset_instrument_specification_selection()[source]

Create and return the dataset TDC selection widgets.

Returns:

Dropdown widget for selecting data mode. pulse_mode (object): Dropdown widget for selecting pulse mode. flightPathLength (object): FloatText widget for flight path length. t0 (object): FloatText widget for t0. max_mc (object): FloatText widget for maximum mc. det_diam (object): FloatText widget for detector diameter.

Return type:

tdc (object)

pyccapt.calibration.core.widgets.density_field_selection()[source]

Create and return the element dropdown widget for density field selection.

Returns:

Dropdown widget for selecting an element.

Return type:

element (object)

pyccapt.calibration.core.widgets.dropdownWidget(elementsList, dropdownLabel)[source]

Create a dropdown widget for selecting elements.

Parameters:
  • elementsList (list) – List of elements with their corresponding mass/weight. Format: [(‘H’, 1.01), (‘He’, 3.02)]

  • dropdownLabel (str) – Label for the dropdown widget.

Returns:

Dropdown widget object.

Return type:

dropdown (object)

pyccapt.calibration.core.widgets.load_tdc_raw_selection()[source]

Create the dropdown for opting into raw /tdc loading.

The widget has labels (True, False) and resolves to bool values. Pass the widget’s .value to helper_data_loader.load_data via the load_tdc_raw argument. When True, the loader also reads the /tdc group and links it to the /dld group via shared event_group_id so raw rows can later be saved alongside calibrated dld output.

pyccapt.calibration.core.widgets.onClickAdd(b, variables)[source]

Callback function for the ADD button click event. Adds the selected element in the dropdown to a list.

Parameters:

variables (object) – Object of the Variables class.

Returns:

None

pyccapt.calibration.core.widgets.onClickDelete(b, variables)[source]

Callback function for the DELETE button click event. Deletes the selected element in the dropdown from the list. :param variables: Variables object. :type variables: object

Returns:

None

pyccapt.calibration.core.widgets.onClickReset(b, variables)[source]

Callback function for the RESET button click event. Clears the list and deletes all the elements from it. :param variables: Variables object. :type variables: object

Returns:

None

pyccapt.calibration.core.widgets.on_change(change)[source]

Callback function for observing changes in the dropdown widget. Updates the selected element and its corresponding weight/mass based on the dropdown selection.

pyccapt.calibration.core.widgets.on_change_charge(change)[source]

Callback function for observing changes in the dropdown widget for charge selection. Updates the selected charge value.

pyccapt.calibration.core.widgets.on_change_charge_ions_selection(change)[source]

Callback function for observing changes in the dropdown widget for ions selection and charge. Updates the selected charge value.

pyccapt.calibration.core.widgets.on_change_ions_selection(change)[source]

Callback function for observing changes in the dropdown widget for ions selection. Updates the selected element and its corresponding weight/mass based on the dropdown selection.

Module contents

Calibration package public exports.

exception pyccapt.calibration.core.CalibrationError[source]

Bases: Exception

Base class for calibration-related errors.

exception pyccapt.calibration.core.CalibrationInputError[source]

Bases: CalibrationError, ValueError

Raised when caller input is invalid for a calibration workflow.

exception pyccapt.calibration.core.CalibrationStateError[source]

Bases: CalibrationError, RuntimeError

Raised when shared calibration state is incomplete or inconsistent.

class pyccapt.calibration.core.SharedVariablesBase[source]

Bases: object

Shared state helpers used by calibration and visualization workflows.

build_calibration_mask(calibration_mode: str) ndarray[source]

Build a boolean mask from the selected peak range and calibration mode.

clear_calibration_peak_range(calibration_mode: str | None = None) None[source]

Clear one or all stored calibration-only peak windows.

clear_calibration_selection_mask(calibration_mode: str | None = None) None[source]

Clear one or all locked calibration ion masks.

clear_peak_range() None[source]

Reset selected peak window to an unselected state.

ensure_valid_peak_range() None[source]

Validate that a peak range is selected and logically valid.

get_calibration_array(calibration_mode: str) ndarray[source]

Return the selected calibrated array for a calibration mode.

get_calibration_peak_range(calibration_mode: str) tuple[float, float][source]

Return the active peak window for calibration, preferring the stored snapshot.

resolve_result_data_file(filename: str) str[source]

Resolve filename inside result_data_path.

resolve_result_file(filename: str) str[source]

Resolve filename inside result_path.

restore_data_from_backup() DataFrame[source]

Restore the original dataframe snapshot and resynchronize shared arrays.

set_calibration_peak_range(calibration_mode: str, left: float, right: float) tuple[float, float][source]

Store a calibration-only copy of the active peak window for one mode.

set_calibration_selection_mask(calibration_mode: str, mask: ndarray) None[source]

Lock a boolean ion-selection mask for repeated calibration steps.

set_peak_range(left: float, right: float) None[source]

Set selected peak window after validating numeric order.

set_result_data_directory(directory: str | Path) str[source]

Set and return the normalized directory used for data exports.

set_result_directory(directory: str | Path) str[source]

Set and return the normalized directory used for figures and plots.

sync_from_data(data: DataFrame | None = None, *, update_backups: bool = False, clear_selection: bool = True) DataFrame[source]

Synchronize shared arrays from the current dataframe after crop/load/reset operations.

class pyccapt.calibration.core.Variables[source]

Bases: SharedVariablesBase

Container for shared variables across calibration workflows.

property data_name

Backward-compatible alias for dataset_name.

property dld_highVoltage

Backward-compatible alias for legacy camelCase field names.

pyccapt.calibration.core.simulate_mass_spectrum(peaks: Iterable[dict], x_min: float | None = None, x_max: float | None = None, bin_width: float = 0.01, background_amplitude: float = 0.0, background_decay: float = 0.0, poisson_noise: bool = True, seed: int | None = None) DataFrame[source]

Simulate a 1D mass spectrum from Gaussian peaks plus optional exponential background.

Each peak dictionary may contain: - mass or center: peak position in Da - sigma: peak width in Da - intensity or amplitude: peak amplitude