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)[source]
Public helper for stable multi-peak evaluation windows used by auto calibration.
- 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:
- 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')[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.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)[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
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.
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:
objectMatplotlib 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.
- 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.
- class pyccapt.calibration.core.interactive_point_identification.AnnoteFinder(xdata, ydata, annotations, variables, ax=None, xtol=None, ytol=None)[source]
Bases:
AnnotationFinderBackward-compatible class alias with legacy name.
pyccapt.calibration.core.ion_selection module
- pyccapt.calibration.core.ion_selection.chunks(lst, n)[source]
Yield successive n-sized chunks from a list.
- pyccapt.calibration.core.ion_selection.create_formula_latex(aa, num_charge=0)[source]
Create a LaTeX representation of a chemical formula.
- 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:
- 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.
- 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:
- 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:
- 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.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:
- 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:
- 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:
pyccapt.calibration.core.mc_plot module
- class pyccapt.calibration.core.mc_plot.AptHistPlotter(mc_tof, variables=None)[source]
Bases:
objectThis class plots the histogram of the mass-to-charge ratio (mc) or time of flight (tof) data.
Initializes all the attributes of AptHistPlotter.
- Parameters:
mc_tof (numpy.ndarray) – Array for mc or tof data.
variables (share_variables.Variables) – The global experiment variables.
- calculate_noise(fig_size=(9, 5), plot_without_noise=False)[source]
Calculate noise after fitted background subtraction.
- 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.
- 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:
- 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.
- 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.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:
- 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.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.
- pyccapt.calibration.core.widgets.load_tdc_raw_selection()[source]
Create the dropdown for opting into raw
/tdcloading.The widget has labels (
True,False) and resolves toboolvalues. Pass the widget’s.valuetohelper_data_loader.load_datavia theload_tdc_rawargument. When True, the loader also reads the/tdcgroup and links it to the/dldgroup via sharedevent_group_idso 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.
Module contents
Calibration package public exports.
- exception pyccapt.calibration.core.CalibrationError[source]
Bases:
ExceptionBase class for calibration-related errors.
- exception pyccapt.calibration.core.CalibrationInputError[source]
Bases:
CalibrationError,ValueErrorRaised when caller input is invalid for a calibration workflow.
- exception pyccapt.calibration.core.CalibrationStateError[source]
Bases:
CalibrationError,RuntimeErrorRaised when shared calibration state is incomplete or inconsistent.
Bases:
objectShared state helpers used by calibration and visualization workflows.
Build a boolean mask from the selected peak range and calibration mode.
Clear one or all stored calibration-only peak windows.
Clear one or all locked calibration ion masks.
Reset selected peak window to an unselected state.
Validate that a peak range is selected and logically valid.
Return the selected calibrated array for a calibration mode.
Return the active peak window for calibration, preferring the stored snapshot.
Resolve filename inside result_data_path.
Resolve filename inside result_path.
Restore the original dataframe snapshot and resynchronize shared arrays.
Store a calibration-only copy of the active peak window for one mode.
Lock a boolean ion-selection mask for repeated calibration steps.
Set selected peak window after validating numeric order.
Set and return the normalized directory used for data exports.
Set and return the normalized directory used for figures and plots.
Synchronize shared arrays from the current dataframe after crop/load/reset operations.
- class pyccapt.calibration.core.Variables[source]
Bases:
SharedVariablesBaseContainer 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: -
massorcenter: peak position in Da -sigma: peak width in Da -intensityoramplitude: peak amplitude