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 (LAUNCHER DASHBOARD)
- create_card(title_text, sub_text, object_name)[source]
Crea una tarjeta de módulo usando QLabels internos para soportar formato rico.
- 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.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.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.get_concentration_matrix_sequential(x_nl, t, numExp, use_art=False, artifact_mode='both')[source]
- fit.get_concentration_matrix_oscillation(x_nl, t, numExp, use_art=False, artifact_mode='both')[source]
- fit.eval_varpro_model(C, data_c_T, enforce_nonneg=False, numExp=None)[source]
Ejecuta la Proyección Variable. Si enforce_nonneg es True, fuerza a que las amplitudes de las especies (SAS) sean >= 0, pero permite que el artefacto coherente fluya libremente.
- fit.get_coherent_artifact(t, t0, w, mode='both')[source]
Genera las bases matemáticas para el artefacto coherente.
- modestr
- ‘raman’ → solo φ₀ (IRF gaussiana). Absorbe Raman espontáneo
y absorción de 2 fotones.
- ‘xpm’ → solo φ₁ y φ₂ (1ª y 2ª derivada de la IRF). Absorbe
Cross-Phase Modulation y efectos dispersivos.
‘both’ → las tres bases (defecto). Caso general TAS broadband.
- class fit.KMatrixModel(name='Modelo Personalizado')[source]
Bases:
object- add_transition(source, target, param_type='tau', label='')[source]
Añade una transferencia de población entre dos estados.
- build_parameter_list()[source]
Analiza las transiciones y extrae la lista única de parámetros a optimizar.
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.FitWorker(*args: Any, **kwargs: Any)[source]
Bases:
QThreadHilo secundario para ejecutar el ajuste de Mínimos Cuadrados (VarPro) sin bloquear la interfaz gráfica principal.
- progress_update
alias of
int
- finished_success
alias of
object
- finished_error
alias of
str
- 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:
QDialogDialog to setup parameters for comparing kinetics across multiple datasets. Allows user to pick target wavelength, normalization, titles, labels, and colors.
- class GlobalFitClassGui.PaperPlotterWindow(*args: Any, **kwargs: Any)[source]
Bases:
QDialogAdvanced Drag & Drop Publication-Quality Plotter for Kinetics Traces. Works 100% autonomously. Allows users to customize dimensions, palettes, and crop the Y-axis (ΔA) with high precision.
- class GlobalFitClassGui.StateNode(*args: Any, **kwargs: Any)[source]
Bases:
QGraphicsRectItemCaja gráfica que representa un estado físico (S1*, 3CT, etc.)
- class GlobalFitClassGui.TransitionEdge(*args: Any, **kwargs: Any)[source]
Bases:
QGraphicsLineItemFlecha gráfica inteligente que conecta dos estados con dirección.
- class GlobalFitClassGui.KineticCanvas(*args: Any, **kwargs: Any)[source]
Bases:
QGraphicsViewLienzo interactivo (Diagrama de Jablonski / Grotrian)
- class GlobalFitClassGui.ModelBuilderDialog(*args: Any, **kwargs: Any)[source]
Bases:
QDialogVentana interactiva Dual: Modo Tabla y Modo Visual (Canvas) para construir modelos cinéticos in-situ.
- class GlobalFitClassGui.ParameterIdentifiabilityDialog(*args: Any, **kwargs: Any)[source]
Bases:
QDialogDiálogo para analizar la identificabilidad de un parámetro cinético mediante perfiles de verosimilitud (profile likelihood), en vez de confiar únicamente en el error basado en la covarianza.
- 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.
- export_spectrum_at_delay()[source]
Exporta el espectro (ΔA vs Wavelength) al delay más cercano al introducido por el usuario, como un fichero .txt. Si ya existe un resultado de fit, incluye también el Fit y el Residual a ese mismo delay para comparación directa en el mismo archivo.
- open_identifiability_dialog()[source]
Abre el diálogo de análisis de identificabilidad (profile likelihood).
- open_standalone_plotter()[source]
Lanza el módulo de gráficos de publicación de forma 100% independiente.
- open_sasdas_plotter()[source]
Lanza el módulo de maquetación de espectros SAS/DAS de forma autónoma.
- run_svd()[source]
Executes Singular Value Decomposition (SVD) on the active dataset to identify components.
- open_visual_model_builder()[source]
Abre la cuadrícula de diseño y guarda el modelo compilado en memoria.
- apply_baseline_correction()[source]
Performs a baseline correction based on the spinbox value and replots the data.
- remove_active_dataset()[source]
Safely removes the currently selected dataset from memory without restarting.
- compare_kinetics()[source]
Compara cinéticas de múltiples archivos para una lambda específica con personalización total.
- 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.
- compute_profile_likelihood(param_idx, n_steps=15, confidence=0.95, span_sigma=6, progress_callback=None)[source]
Calcula el intervalo de verosimilitud-perfil (profile likelihood) para el parámetro cinético param_idx.
A diferencia del error basado en covarianza (que asume que el chi-cuadrado se comporta como una parábola simétrica alrededor del óptimo), este método fija el parámetro en una rejilla de valores y REAJUSTA todos los demás parámetros cinéticos libres en cada punto. El intervalo de confianza es la región donde el chi-cuadrado no empeora más de lo que el azar explicaría al nivel de confianza dado (test de razón de verosimilitudes, 1 g.d.l.).
- show_results_summary()[source]
Displays a popup window detailing the final global parameters derived from the fit.
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.