Referencia de la API
Esta sección documenta automáticamente los módulos, clases y funciones del código fuente de Ultrafast Spectroscopy Analyzer.
Módulo Principal
Created on Sun Oct 12 16:25:52 2025
@author: Alejandro
- class UltrafastSpectroscopyAnalyzer.MainApp(*args: Any, **kwargs: Any)[source]
Bases:
QMainWindowMain Window (DASHBOARD)
Serves as the central hub for the Ultrafast Spectroscopy Analyzer suite. Provides a graphical menu to launch different specialized analysis tools (FLUPS, TAS, Global Fit, and 2D Mapper).
- create_card(text)[source]
Creates a stylized, large push button to act as a dashboard card.
- Parameters:
text (str) – The label text to display on the button.
- Returns:
The configured button widget.
- Return type:
QPushButton
- class UltrafastSpectroscopyAnalyzer.FLUPSAnalyzer(*args: Any, **kwargs: Any)[source]
Bases:
QMainWindowMain application window for FLUPS (Fluorescence Upconversion Spectroscopy) analysis. Provides an interactive GUI to load data, visualize 2D maps, fit time-zero (t0) dispersion curves, and explore kinetics/spectra dynamically.
- on_draw(event)[source]
Captures the background for Blitting with anti-recursion protection.
- Parameters:
event – The matplotlib draw event.
- draw_animated_artists()[source]
Draws only the animated (moving) elements over the cached background.
- eventFilter(obj, event)[source]
Intercepts specific events from monitored widgets.
- Parameters:
obj – The QObject receiving the event.
event – The QEvent object.
- Returns:
True if event was handled, False otherwise.
- Return type:
bool
- update_n_levels(value)[source]
Updates the number of levels for the discrete map and redraws it, respecting the visible range.
- update_wl_range()[source]
Updates the visible data variables based on sliders and calls plot_map to redraw everything correctly.
- enable_point_selection()[source]
Activates the mode allowing the user to select t0 points on the plot.
- update_small_cuts(x, y, WL_sel=None, data_sel=None)[source]
Full update after a click event.
- Parameters:
x (float) – The clicked X coordinate.
y (float) – The clicked Y coordinate.
WL_sel (numpy.ndarray, optional) – Selected Wavelength slice.
data_sel (numpy.ndarray, optional) – Selected data slice.
- on_click_map(event)[source]
Registers points on the map (left adds, right deletes last) and updates cuts.
- on_move_map(event)[source]
Handles mouse movement over the plot to update cursors and slices dynamically.
- Parameters:
event – The matplotlib mouse motion event.
- fit_t0_points()[source]
Fits the selected points to a t0 curve and saves the extracted/corrected data.
- class UltrafastSpectroscopyAnalyzer.TASAnalyzer(*args: Any, **kwargs: Any)[source]
Bases:
FLUPSAnalyzerTransient Absorption Spectroscopy (TAS) Analyzer.
Inherits from FLUPSAnalyzer but specializes in handling TAS data, which includes simultaneous loading and dynamic subtraction of solvent data, pump fringe removal, and real-time amplitude/shift adjustments.
- eventFilter(obj, event)[source]
Intercepts click events on the Amplitude and Shift labels.
- Parameters:
obj – The QObject receiving the event.
event – The QEvent object.
- Returns:
True if event was handled, False otherwise.
- Return type:
bool
- switch_analyzer()[source]
Switches between FLUPSAnalyzer and TASAnalyzer without closing the main application process.
- convert_dat_to_csv(file_path)[source]
Converts a .dat file into a .csv file structured for TAS analysis.
- Parameters:
file_path (str) – The path to the original .dat file.
- Returns:
The path to the newly created .csv file, or None if conversion fails.
- Return type:
str or None
- get_base_dir()[source]
Returns the directory containing the measurement CSV. Automatically creates ‘fit’ and ‘plots’ subfolders if they do not exist.
- Returns:
(base_dir, fit_dir, plots_dir) paths.
- Return type:
tuple
- remove_pump_fringe()[source]
Prompts the user for a central wavelength and width to mask out the pump scatter artifact. The masked region is set to near-zero (1e-10) to avoid division by zero errors.
- load_file()[source]
Loads both the measurement data and the corresponding solvent data. Handles automatic deduplication, sorting, and initial UI setup for TAS data.
- fit_t0_points()[source]
Fits selected time-zero points and saves the corrected matrix. Overrides the base FLUPS method to ensure the solvent-subtracted base data is used.
- update_am_sf()[source]
Recalculates the base TAS data by subtracting the interpolated solvent matrix scaled by Amplitude (AM) and shifted in time (SF).
- plot_map(show_fit=False)[source]
Draws the main interactive 2D map (SymLog in Y) with support for toggling between Corrected and Original modes.
- Parameters:
show_fit (bool, optional) – Unused flag kept for backward compatibility.
- on_draw(event)[source]
Captures the background for blitting when the entire figure is redrawn.
- Parameters:
event – The matplotlib draw event.
- draw_animated_artists()[source]
Helper function to draw only the dynamic elements over the cached background.
- update_small_cuts(x, y, WL_sel=None, data_sel=None)[source]
Performs a full (slow) update for clicks or slider changes.
- Parameters:
x (float) – The X coordinate.
y (float) – The Y coordinate.
WL_sel – Unused parameter kept for signature compatibility.
data_sel – Unused parameter kept for signature compatibility.
Núcleo de Análisis (core_analysis)
- core_analysis.read_csv_file(path)[source]
Reads and cleans data from a single CSV file.
It assumes the first column contains Wavelengths (WL) and the headers of the subsequent columns represent Time Delays (TD).
- Parameters:
path (str) – The file path to the CSV file.
- Returns:
- A tuple containing:
WL (numpy.ndarray): 1D array of Wavelengths.
TD (numpy.ndarray): 1D array of Time Delays.
data (numpy.ndarray): 2D array of the main data matrix with shape (n_wl, n_td).
- Return type:
tuple
- core_analysis.load_from_paths(data_path, wl_path, td_path)[source]
Loads data from three separate files: main data matrix, wavelengths, and time delays.
This function automatically detects the orientation of the data matrix and transposes it if necessary to match the sizes of the WL and TD arrays. If dimensions do not match perfectly, it pads with zeros or truncates as needed.
- Parameters:
data_path (str) – Path to the 2D data matrix file.
wl_path (str) – Path to the 1D wavelength array file.
td_path (str) – Path to the 1D time delay array file.
- Returns:
- A tuple containing:
data_arr (numpy.ndarray): 2D array with shape (n_wl, n_td).
wl (numpy.ndarray): 1D array of Wavelengths.
td (numpy.ndarray): 1D array of Time Delays.
- Return type:
tuple
- core_analysis.load_data(auto_path=None, data_path=None, wl_path=None, td_path=None)[source]
Master function to load data either from a single comprehensive CSV or from three separate files.
- Parameters:
auto_path (str, optional) – Path to a single CSV containing WL, TD, and data.
data_path (str, optional) – Path to the 2D data matrix file.
wl_path (str, optional) – Path to the 1D wavelength array file.
td_path (str, optional) – Path to the 1D time delay array file.
- Returns:
data (2D), WL (1D), TD (1D)
- Return type:
tuple
- Raises:
ValueError – If no valid files are provided or reading fails entirely.
- core_analysis.eV_a_nm(E_eV)[source]
Converts energy in electron-volts (eV) to wavelength in nanometers (nm).
- Parameters:
E_eV (numpy.ndarray or float) – Energy in eV.
- Returns:
Corresponding wavelength in nm.
- Return type:
numpy.ndarray or float
- core_analysis.t0_model(w, a, b, c, d)[source]
Proposed non-linear model for time-zero (t0) dispersion correction.
Formula: t0 = a * sqrt((b*w^2 - 1) / (c*w^2 - 1)) + d
- Parameters:
w (array-like) – Wavelength points.
a (float) – Fitting parameters.
b (float) – Fitting parameters.
c (float) – Fitting parameters.
d (float) – Fitting parameters.
- Returns:
Computed t0 values. Returns NaN where the expression is mathematically invalid.
- Return type:
numpy.ndarray
- core_analysis.apply_t0_correction_poly(popt, WL, TD, data)[source]
Applies a polynomial time-zero (t0) correction to the dataset.
- Parameters:
popt (array-like) – Polynomial coefficients (must be of length 5, degree 4).
WL (numpy.ndarray) – Wavelength array.
TD (numpy.ndarray) – Time Delay array.
data (numpy.ndarray) – 2D array of the main data matrix.
- Returns:
- A tuple containing:
corrected (numpy.ndarray): The t0-corrected 2D data matrix.
t0_lambda (numpy.ndarray): The calculated t0 offset for each wavelength.
- Return type:
tuple
- core_analysis.apply_t0_correction_nonlinear(popt, WL, TD, data)[source]
Applies a non-linear time-zero (t0) correction to the dataset using t0_model.
- Parameters:
popt (list or array-like) – Optimized parameters [a, b, c, d] for the non-linear model.
WL (numpy.ndarray) – Wavelength array.
TD (numpy.ndarray) – Time Delay array.
data (numpy.ndarray) – 2D array of the main data matrix.
- Returns:
- A tuple containing:
corrected (numpy.ndarray): The t0-corrected 2D data matrix.
t0_lambda (numpy.ndarray): The calculated t0 offset for each wavelength.
- Return type:
tuple
- core_analysis.fit_t0(w_points, t0_points, WL, TD, data, min_points_nonlinear=4, mode='auto')[source]
Fits time-zero (t0) dispersion based on user-selected points (w_points, t0_points).
The function attempts to fit the non-linear model (t0_model) if there are enough points. If the non-linear fit fails or lacks sufficient points, it falls back to a polynomial fit of up to degree 4.
- Parameters:
w_points (array-like) – Wavelengths (nm) of the chosen data points.
t0_points (array-like) – Corresponding delays (ps) of the chosen data points.
WL (numpy.ndarray) – Full wavelength array (from read_csv_file or load_from_paths).
TD (numpy.ndarray) – Full time delay array.
data (numpy.ndarray) – Full 2D data matrix.
min_points_nonlinear (int) – Minimum number of points required to attempt the non-linear model. Defaults to 4.
mode (str) – Fitting mode strategy. ‘auto’ (default), ‘nonlinear’ (force non-linear), or ‘poly’ (force polynomial).
- Returns:
- A dictionary containing the fitting results:
’method’: String indicating the method used (‘nonlinear’ or ‘polyX’).
’popt’: The optimized coefficients/parameters.
’fit_x’: High-resolution X array used for plotting the fit line.
’fit_y’: High-resolution Y array representing the fit curve.
’corrected’: The newly corrected 2D data matrix.
’t0_lambda’: The calculated t0 vector for every wavelength in WL.
- Return type:
dict
Ajuste y Modelado (fit)
- fit.load_npy(parent=None, normalize_per_wl=True)[source]
Opens a dialog to load a treated data file (.npy).
- Parameters:
parent (QWidget, optional) – The parent widget for the dialog. Defaults to None.
normalize_per_wl (bool, optional) – (Currently unused) Flag to normalize per wavelength.
- Returns:
A tuple containing: - data_c (numpy.ndarray): Data matrix. - TD (numpy.ndarray): Time delay vector. - WL (numpy.ndarray): Wavele ngth vector. - base_dir (str): Directory of the selected file.
- Return type:
tuple
- Raises:
ValueError – If the user cancels the file selection.
- fit.crop_spectrum(data_c, WL, WLmin, WLmax)[source]
Crops the spectral data to a specific wavelength range.
- Parameters:
data_c (numpy.ndarray) – Original data matrix (Times x Wavelengths).
WL (numpy.ndarray) – Wavelength vector.
WLmin (float) – Lower wavelength limit.
WLmax (float) – Upper wavelength limit.
- Returns:
Cropped data matrix and cropped wavelength vector.
- Return type:
tuple
- fit.crop_kinetics(data_c, TD, TDmin, TDmax)[source]
Crops the kinetics to a specific time range.
- Parameters:
data_c (numpy.ndarray) – Original data matrix (Times x Wavelengths).
TD (numpy.ndarray) – Time delay vector.
TDmin (float) – Lower time limit.
TDmax (float) – Upper time limit.
- Returns:
Cropped data matrix and cropped time vector.
- Return type:
tuple
- fit.binning(data_c, WL, bin_size)[source]
Bins adjacent wavelength channels to improve the signal-to-noise ratio.
- Parameters:
data_c (numpy.ndarray) – Original data matrix.
WL (numpy.ndarray) – Wavelength vector.
bin_size (int) – Number of channels to bin together.
- Returns:
Averaged data matrix and averaged wavelength vector.
- Return type:
tuple
- fit.convolved_exp_vectorized(t, t0, taus, w)[source]
Calculates a sum of exponential decays convolved with a Gaussian IRF. VERSIÓN HÍBRIDA ESTABLE CON BROADCASTING CORREGIDO.
- fit.eval_global_model(x, t, numExp, numWL, t0_choice_str)[source]
Evaluates the global parallel model (DAS - Decay Associated Spectra).
Calculates the 2D data surface (Time x Wavelength) based on shared lifetimes and independent amplitudes per wavelength.
- Parameters:
x (list or numpy.ndarray) – Array of fitting parameters (w, t0, taus, amplitudes).
t (numpy.ndarray) – Time delay vector.
numExp (int) – Number of exponential components.
numWL (int) – Number of wavelengths to fit.
t0_choice_str (str) – ‘Yes’ for fitting with chirp correction (variable t0 per wavelength), any other value for standard global fitting (single shared t0).
- Returns:
Simulated data matrix (Time x Wavelength).
- Return type:
numpy.ndarray
- fit.get_sequential_populations(t, t0, w, taus)[source]
Calculates the populations for a sequential model (A -> B -> C…).
Uses a dynamic Bateman equations generator to support any number of exponential components.
- Parameters:
t (numpy.ndarray) – Time vector.
t0 (float) – Time zero.
w (float) – Width of the IRF.
taus (list) – List of lifetimes for each sequential species.
- Returns:
List where each element is the population over time for the corresponding species.
- Return type:
list of numpy.ndarray
- fit.eval_sequential_model(x, t, numExp, numWL, t0_choice_str)[source]
Evaluates the sequential model (SAS - Species Associated Spectra).
- Parameters:
x (list) – Parameter array.
t (numpy.ndarray) – Time vector.
numExp (int) – Number of species in the cascade.
numWL (int) – Number of wavelengths.
t0_choice_str (str) – ‘Yes’ for chirp correction mode.
- Returns:
Simulated data matrix.
- Return type:
numpy.ndarray
- fit.damped_oscillation(t, t0, alpha, omega, phi, w)[source]
Calculates a damped oscillation with a smooth step (approximating IRF convolution).
Equation used: $S(t) = 0.5 cdot (1 + ext{erf}((t-t0)/(sqrt{2}w))) cdot exp(-lpha(t-t0)) cdot sin(omega(t-t0) + phi)$
- Parameters:
t (numpy.ndarray) – Time vector.
t0 (float) – Time zero (start of the oscillation).
alpha (float) – Damping rate.
omega (float) – Angular frequency of the oscillation.
phi (float) – Initial phase (in radians).
w (float) – Width of the IRF (controls the smoothness of the onset).
- Returns:
Vector with the damped oscillatory signal.
- Return type:
numpy.ndarray
- fit.eval_oscillation_model(x, t, numExp, numWL, t0_choice_str)[source]
Evaluates a model combining parallel exponential decays and a damped oscillation.
- Parameters:
x (list) – Model parameters (w, t0, taus, alpha, omega, phi, local amplitudes).
t (numpy.ndarray) – Time vector.
numExp (int) – Number of exponential decays.
numWL (int) – Number of wavelengths.
t0_choice_str (str) – Must be ‘No’ (Chirp is not yet implemented for this model).
- Returns:
Simulated data matrix.
- Return type:
numpy.ndarray
- Raises:
NotImplementedError – If attempted to use with t0_choice_str == ‘Yes’.
Interfaz Gráfica de Ajuste (GlobalFitClassGui)
- class GlobalFitClassGui.Surface3DWindow(*args: Any, **kwargs: Any)[source]
Bases:
QDialogIndependent window to visualize the 3D plot without blocking the main application.
- __init__(xs, ys, zs, scale='linear', parent=None)[source]
Initializes the 3D surface plotting window.
- Parameters:
xs (numpy.ndarray) – X-axis array (e.g., Wavelengths).
ys (numpy.ndarray) – Y-axis array (e.g., Time Delays).
zs (numpy.ndarray) – 2D Z-axis matrix (e.g., Transient Absorption data).
scale (str, optional) – The scale of the Y-axis (‘linear’ or ‘symlog’). Defaults to ‘linear’.
parent (QWidget, optional) – Parent widget. Defaults to None.
- class GlobalFitClassGui.PlotViewerWindow(*args: Any, **kwargs: Any)[source]
Bases:
QDialogVentana independiente para visualizar gráficos SAS/DAS sin bloquear la app.
- class GlobalFitClassGui.TraceExplorerWindow(*args: Any, **kwargs: Any)[source]
Bases:
QDialogExplorador interactivo de cinéticas sin bloquear la interfaz.
- class GlobalFitClassGui.CompareSetupDialog(*args: Any, **kwargs: Any)[source]
Bases:
QDialogCuadro de diálogo interactivo con Drag & Drop y selector de color.
- class GlobalFitClassGui.GlobalFitPanel(*args: Any, **kwargs: Any)[source]
Bases:
QDialogGlobal Fit Analysis Panel.
Provides a comprehensive UI for loading kinetic data, applying pre-processing steps, setting up global fitting models (Parallel, Sequential, Oscillation), running SVD, executing the fit pipeline, and exploring the results and residuals.
- run_svd()[source]
Executes Singular Value Decomposition (SVD) on the active dataset to identify components.
- apply_baseline_correction()[source]
Performs a baseline correction based on the spinbox value and replots the data.
- compare_kinetics()[source]
Compara cinéticas de múltiples archivos para una lambda específica con personalización total.
- on_mouse_move(event)[source]
Updates the status label with real-time mouse coordinates and data values on the map.
- run_fit_pipeline()[source]
Main execution pipeline: Preprocess, set model parameters, and run the optimization.
- run_batch_pipeline()[source]
Ejecuta el ajuste para todos los archivos cargados de forma secuencial.
Herramientas de Mapas (maps_from_timescans)
- class maps_from_timescans.XFELProcessor[source]
Bases:
objectHandles the backend processing of X-ray Free-Electron Laser (XFEL) kinetic data. Extracts time arrays and specific signals from a batch of .npy files to construct 2D maps.
- process(file_paths, energies, keys, time_scale=1.0)[source]
Reads data from multiple .npy files and constructs a 2D data matrix.
- Parameters:
file_paths (list of str) – Paths to the .npy data files.
energies (list of float) – List of energy or wavelength values corresponding to each file.
keys (dict) – Dictionary specifying the dictionary keys to look for inside the .npy files. Expected keys: ‘time’, ‘direct_sig’, ‘es’ (Excited State), ‘gs’ (Ground State).
time_scale (float, optional) – Scaling factor applied to the time array. Defaults to 1.0.
- Returns:
- A tuple containing:
common_td (numpy.ndarray): 1D array of filtered Time Delays.
energies (numpy.ndarray): 1D array of Energies/Wavelengths.
M (numpy.ndarray): 2D data matrix containing the compiled signals.
- Return type:
tuple
- Raises:
KeyError – If a required key is missing from the .npy dictionary.
- analyze_units(file_path, time_key)[source]
Performs a statistical analysis on the time vector of a single file to infer its physical units.
- Parameters:
file_path (str) – Path to the .npy file to analyze.
time_key (str) – The dictionary key used to access the time array within the file.
- Returns:
- A tuple (unit_string, description_string) detailing the inferred unit
(ps or fs) and the calculated statistics.
- Return type:
tuple
- class maps_from_timescans.AppWindow(*args: Any, **kwargs: Any)[source]
Bases:
QMainWindowMain application window built with PyQt5. Provides a GUI for users to load XFEL .npy files, specify internal dictionary keys, map energies, generate a 2D contour map, and save the output.
- validate_counts()[source]
Validates if the number of manually inputted energies matches the number of loaded files. Updates the UI status label with color-coded feedback.
- import_energies()[source]
Opens a file dialog to read an energy vector from a text/csv file and populates the line edit.
- load_files()[source]
Opens a file dialog for the user to select multiple .npy files and updates the list widget.