From 79dd0ee540fbfce29427dd9499683bfcff4ff561 Mon Sep 17 00:00:00 2001 From: manuel Date: Fri, 11 Sep 2026 21:39:24 +0000 Subject: [PATCH] Upload files to "/" --- bd_fresnel_core.py | 1157 +++++++++++++++++++++++++++++ bd_fresnel_gui.py | 1675 ++++++++++++++++++++++++++++++++++++++++++ set_params_dialog.py | 164 +++++ 3 files changed, 2996 insertions(+) create mode 100644 bd_fresnel_core.py create mode 100644 bd_fresnel_gui.py create mode 100644 set_params_dialog.py diff --git a/bd_fresnel_core.py b/bd_fresnel_core.py new file mode 100644 index 0000000..b9f5c8d --- /dev/null +++ b/bd_fresnel_core.py @@ -0,0 +1,1157 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +bd_fresnel_core.py +=================== + +Physics/computation engine for the Beam Deflection Fresnel-propagation +pump-probe simulator. Translated from the original MATLAB sources: + + I_e_func.m + excite_prop.m + BD_3_level_triplet.m + BD_exp_rise_decay.m + BD_librational.m + BD_vibrational.m + BD_Fresnel_func_ni.m + +Calculates the cross-correlation signal of a beam-deflection pump-probe +experiment with nonlinear refraction (NLR) and two-photon absorption +(2PA), including group-velocity mismatch (GVM). Uses Fresnel +propagation to the detector. Ten selectable "mechanisms" (electronic, +collisional, librational, reorientational, vibrational, a 3-level + +triplet excited-state-absorption system, and three generic +exponential-rise/decay variants) can be combined. + +Original references: + 1. Reichert, M., et al. (2014). "Temporal, spectral, and + polarization dependence of the nonlinear optical response of + carbon disulfide." Optica 1(6): 436. + 2. Ferdinandus, M. R., et al. (2013). "Beam deflection measurement + of time and polarization resolved ultrafast nonlinear + refraction." Opt Lett 38(18): 3518-3521. + +------------------------------------------------------------------------- +NOTES ON THE MATLAB -> PYTHON TRANSLATION +------------------------------------------------------------------------- +* MATLAB's ndgrid(a,b,c,d) preserves argument order (dimension i varies + with input i) -> numpy.meshgrid(a,b,c,d, indexing='ij'). + MATLAB's meshgrid(a,b,c) SWAPS the first two dimensions relative to + argument order -> numpy.meshgrid(a,b,c) with the default + indexing='xy' (numpy's default already matches MATLAB's meshgrid + convention). +* The main grid throughout BD_Fresnel_func_ni is built with ndgrid(Y, + X,T,T_d), so array axis 0 <-> Y, axis 1 <-> X, axis 2 <-> T, axis 3 + <-> T_d. This axis order is preserved exactly (axis 0 is NOT the + x-axis) to match the original numerically. +* Inside BD_3_level_triplet, the original code builds T_grid via + MATLAB's (axis-swapping) meshgrid(x,y,tau_d) and then indexes it + with a loop variable m that ranges over length(x) but is used to + slice meshgrid's first (y-sized) dimension. Since x and y always + have equal length at every call site in this application, this is + numerically harmless -- but the *net effect* is that the resulting + T_grid ends up indexed (y, x, tau_d), i.e. consistent with the outer + ndgrid(Y,X,T,T_d) convention despite its variable name/declared + shape suggesting (x, y, tau_d). This translation reproduces that + same net (y, x, tau_d) result directly and explicitly, rather than + replicating the confusing double-indexing trick verbatim -- the + output is numerically equivalent to the original MATLAB. See + `_build_esa_time_grid` below. +* MATLAB's ode15s (stiff solver), when given a tspan with more than 2 + elements, returns the solution evaluated at exactly those points. + When given a 2-element tspan, it returns the solution at whatever + points its adaptive step control chose. BD_3_level_triplet exploits + this: the very first solve uses a 2-point tspan and the resulting + adaptive time grid is then reused (unchanged, since >2-point tspans + echo back the same points) as a fixed grid for every subsequent + solve. This is replicated with scipy.integrate.solve_ivp(method= + 'BDF'): the first call omits t_eval (letting the adaptive stepper + choose its own points, exposed via sol.t), and every subsequent call + passes t_eval=. +* griddedInterpolant (1D, default linear, default LINEAR extrapolation) + -> scipy.interpolate.interp1d(..., kind='linear', + fill_value='extrapolate'). +* conv(a, b, 'same') on equal-length a, b -> numpy.convolve(a, b, + mode='same') (identical for equal-length inputs). +* coth(x) -> 1 / numpy.tanh(x). +* heaviside(x) (MATLAB's numeric heaviside is 0.5 at x==0) -> + numpy.heaviside(x, 0.5). +""" + +import time +import datetime + +import numpy as np +import scipy.fft +import scipy.constants +from scipy.integrate import solve_ivp +from scipy.interpolate import interp1d, RegularGridInterpolator +from scipy.signal import fftconvolve +from scipy.special import erf +from dataclasses import dataclass, field +from typing import List +import mpmath + +# Physical constants, taken from scipy.constants rather than +# transcribed. Both are exact defining constants of the SI (c since +# 1983, h since the 2019 redefinition), so there is no CODATA revision +# to track and no rounding to choose -- but see the note below on what +# the original MATLAB used. +# +# The original hard-coded these in three places and got two of them +# wrong: +# * BD_3_level_triplet.m used h = 6.626070e-34, the exact value +# truncated to 7 significant figures (2.3e-8 relative error), and +# labelled its units "(J/s)" where Planck's constant is in J s. +# * BD_Fresnel_GUI.m's calc_beam_params used c = 299797548 m/s, a +# digit transposition of 299792458 (1.7e-5 relative error). Its +# other two definitions of c, in BD_Fresnel_func_ni.m and +# BD_3_level_triplet.m, were correct. +# Both are corrected here; see calc_beam_params for the effect. +c = scipy.constants.c # speed of light in vacuum [m/s] +h = scipy.constants.h # Planck constant [J s] + +# NumPy >= 2.0 renamed trapz() to trapezoid(); keep both names usable. +_trapz = getattr(np, "trapezoid", None) or np.trapz + + +def heaviside(x): + return np.heaviside(x, 0.5) + + +def _diag_print(message: str) -> None: + """Timestamped progress line, equivalent to the original's + disp([datestr(now),': ...']) diagnostic logging.""" + print(f"{datetime.datetime.now()}: {message}") + + +# ============================================================================= +# CONFIGURATION +# ============================================================================= + +@dataclass +class Mechanism: + """One selected mechanism slot. `param` holds up to 10 raw values + exactly as entered in the GUI (i.e. NOT yet scaled by the e-11, + e-19, etc. factors baked into the mechanism dispatch below).""" + name: str = "None (both)" + param: List[float] = field(default_factory=lambda: [0.0] * 10) + + +# The 10 selectable mechanisms, in the same order as the original +# set_params_GUI.m switch-case / mechanism_names list. Matched exactly +# (including spelling/spacing) against the case labels dispatched on +# in BD_Fresnel_func_ni.m above. +MECHANISM_NAMES = [ + "None (both)", + "Electronic (both)", + "Collisional (NLR)", + "Librational (NLR)", + "Reorientational (NLR)", + "Vibrational (NLR)", + "ESA - 3 level + triplet (both)", + "Exponential rise/decay (NLA)", + "Exponential rise/decay (NLR)", + "Exponential rise/decay (both)", +] + +# Per-mechanism (parameter name, unit label) pairs, in order, matching +# the param_names/param_units cell arrays in set_params_GUI.m exactly. +MECHANISM_PARAM_SPECS = { + "None (both)": [], + "Electronic (both)": [ + ("alpha_2e", "e-11 m/W"), ("n_2e", "e-19 m^2/W"), + ], + "Collisional (NLR)": [ + ("n_2c", "e-19 m^2/W"), ("tau_cr", "fs"), ("tau_cf", "fs"), + ], + "Librational (NLR)": [ + ("n_2l", "e-19 m^2/W"), ("omega_0", "ps^-1"), ("sigma", "ps^-1"), ("tau_lf", "fs"), + ], + "Reorientational (NLR)": [ + ("n_2r", "e-19 m^2/W"), ("tau_rr", "fs"), ("tau_rf", "fs"), + ], + "Vibrational (NLR)": [ + ("n_2v", "e-19 m^2/W"), ("w_0v", "ps^-1"), ("tau_vf", "fs"), + ], + "ESA - 3 level + triplet (both)": [ + ("alpha_2", "e-11 m/W"), ("N0", "e+22 m^-3"), + ("sigma_S_01", "e-21 m^2"), ("sigma_S_12", "e-21 m^2"), ("sigma_T_12", "e-21 m^2"), + ("tau_S_10", "ps"), ("tau_S_21", "ps"), ("tau_ISC", "ps"), ("tau_T_21", "ps"), ("tau_TS", "ps"), + ], + "Exponential rise/decay (NLA)": [ + ("alpha_2_exp", "e-11 m/W"), ("tau_expr", "fs"), ("tau_expf", "fs"), + ], + "Exponential rise/decay (NLR)": [ + ("n_2_exp", "e-19 m^2/W"), ("tau_expr", "fs"), ("tau_expf", "fs"), + ], + "Exponential rise/decay (both)": [ + ("alpha_2_exp", "e-11 m/W"), ("n_2_exp", "e-19 m^2/W"), ("tau_expr", "fs"), ("tau_expf", "fs"), + ], +} + + +@dataclass +class BDFresnelParams: + """ + Mirrors the MATLAB `handles.params` struct directly -- a single + superset object holding both the raw, GUI-entered values and the + derived/calculated values, passed as-is into BD_Fresnel_func_ni + (which, like the original MATLAB function, only reads the subset + of fields it actually needs). + """ + # --- pump (excitation) beam: raw GUI-entered values --- + E_p: float = 1.36 # pump pulse energy [uJ] + tau_p_FWHM: float = 55.0 # pump pulse width, FWHM of I [fs] + w_0p: float = 246.0 # pump spot size, HW1/e^2 of I [um] + lambda_p: float = 800.0 # pump wavelength [nm] + + # --- probe beam: raw GUI-entered values --- + tau_FWHM: float = 60.0 # probe pulse width, FWHM of I [fs] + w_0: float = 43.0 # probe spot size, HW1/e^2 of I [um] + lambda_: float = 650.0 # probe wavelength [nm] + + # --- material parameters at pump wavelength --- + R_p: float = 0.0 # reflectivity of pump + alpha_p: float = 0.0 # pump linear absorption coefficient [cm^-1] + n_p: float = 1.4533 # refractive index at pump wavelength + dndl_p: float = -0.017284 # dispersion dn/dlambda at pump [um^-1] + alpha_2d: float = 0.0 # pump degenerate 2PA coefficient [1e-11 m/W] + + # --- material parameters at probe wavelength --- + R: float = 0.0 # reflectivity of probe + alpha: float = 0.0 # probe linear absorption coefficient [cm^-1] + n: float = 1.4565 # refractive index at probe wavelength + dndl: float = -0.027158 # dispersion dn/dlambda at probe [um^-1] + + # --- system geometry --- + l: float = 1.0 # sample thickness [mm] + d: float = 15.0 # sample -> detector distance [cm] + shift: float = 0.0 # delay-axis (zero-time) shift applied to imported data [fs] + x_0: float = 0.5 # pump-probe x displacement [w_0p] + + # --- derived / calculated values (set by calc_beam_params) --- + tau_p: float = 0.0 # pump pulse width, HW1/e of I [fs] (derived from tau_p_FWHM) + tau: float = 0.0 # probe pulse width, HW1/e of I [fs] (derived from tau_FWHM) + sigma_p: float = 0.0 # pump linear-absorption parameter (unitless) + I_0_p: float = 1.0 # peak pump irradiance [W/m^2] + ng_p: float = 1.0 # group index at pump + ng: float = 1.0 # group index at probe + rho: float = 0.0 # GVM parameter + z_0: float = 0.0 # probe Rayleigh range [m] (display only) + z_0_p: float = 0.0 # pump Rayleigh range [m] (display only) + Tlin: float = 1.0 # linear transmission of probe (display only) + Tlin_p: float = 1.0 # linear transmission of pump (display only) + + # --- simulation grid --- + X_max: float = 5.0 + X_num: int = 50 + T_min: float = -5.0 + T_max: float = 5.0 + T_num: int = 100 + # T_d_min/T_d_max are overwritten at fit time from the imported + # scan's delay range; only T_d_num is a user setting. Its default + # is 150 because that is the value the GUI previously hard-coded + # at fit time, so exposing it as an input changes nothing until + # it is edited. + T_d_min: float = -5.0 + T_d_max: float = 5.0 + T_d_num: int = 150 + + # --- mechanisms (up to n_mech slots) --- + n_mech: int = 7 + mech: List[Mechanism] = field(default_factory=lambda: [Mechanism() for _ in range(7)]) + + # --- imported-data column layout --- + # Which column of the imported file supplies each quantity, 1-based + # exactly as typed in the GUI's "Data columns" box. The defaults + # reproduce the fixed layout the original app assumed: delay first, + # then DeltaE/E, then transmission. + col_tau_d: int = 1 + col_DeltaEoE: int = 2 + col_T: int = 3 + + # Field separator used when reading the file, as typed in the GUI. + # "\t" (backslash-t) means a tab and a blank field means any run of + # whitespace; anything else is used literally. + delimiter: str = "," + + # --- flags / state --- + diagnostics: bool = False + data_imported: bool = False + data_fit: bool = False + + # --- file paths --- + filename: str = "" + pathname: str = "" + import_filepath: str = "" + + +# ============================================================================= +# excite_prop.m / I_e_func.m +# ============================================================================= + +def I_e_func(z, t, I_0_e, v_e, v_p, tau_e): + """Irradiance of the excitation (pump) pulse as a function of time + and sample depth z, accounting for group-velocity walk-off.""" + return I_0_e * np.exp(-((t - z / v_e + z / v_p) ** 2) / tau_e ** 2) + + +def excite_prop(t, y, z, I_0_e, v_e, v_p, tau_e, E_photon, + sigma_S_01, sigma_S_12, sigma_T_12, + tau_ISC, tau_S_10, tau_S_21, tau_TS, tau_T_21, alpha_2): + """Right-hand side of the 5-level population rate-equation ODE + system (N_S0, N_S1, N_S2, N_T1, N_T2), for use with an ODE solver.""" + I_e = I_e_func(z, t, I_0_e, v_e, v_p, tau_e) + + c1 = sigma_S_01 / E_photon * I_e * y[0] # absorption S0 -> S1 + c2 = sigma_S_12 / E_photon * I_e * y[1] # absorption S1 -> S2 + c3 = sigma_T_12 / E_photon * I_e * y[3] # absorption T1 -> T2 + c4 = y[1] / tau_ISC # intersystem crossing S1 -> T1 + c5 = y[1] / tau_S_10 # decay S1 -> S0 + c6 = y[2] / tau_S_21 # decay S2 -> S1 + c7 = y[3] / tau_TS # decay T1 -> S0 + c8 = y[4] / tau_T_21 # decay T2 -> T1 + c9 = alpha_2 / (2 * E_photon) * I_e ** 2 # two-photon absorption + + # NOTE: c9 appears with the same sign in both dN[0] and dN[2], + # exactly as in the original excite_prop.m -- preserved verbatim. + dN = np.array([ + -c1 + c5 + c7 + c9, + c1 - c2 - c4 - c5 + c6, + c2 - c6 + c9, + -c3 + c4 - c7 + c8, + c3 - c8, + ]) + return dN + + +# ============================================================================= +# BD_exp_rise_decay.m / BD_librational.m / BD_vibrational.m +# ============================================================================= + +def BD_exp_rise_decay(alpha_2_exp, n_2_exp, tau_exp_r, tau_exp_f, tau_p, T1): + """Generic exponential rise/decay response function. Returns a + complex array: Re = NLR contribution, Im = NLA contribution.""" + T1 = np.asarray(T1, dtype=float) + if (abs(n_2_exp) + abs(alpha_2_exp)) != 0 and tau_exp_r > 0 and tau_exp_f > 0: + t_exp_r = tau_exp_r / tau_p + t_exp_f = tau_exp_f / tau_p + + H = heaviside(T1) + r_exp = H * (1 - np.exp(-H * T1 / t_exp_r)) * np.exp(-H * T1 / t_exp_f) + C_exp = 1 / (t_exp_f ** 2 / (t_exp_f + t_exp_r)) + R_exp = (n_2_exp + alpha_2_exp * 1j) * C_exp * r_exp + else: + R_exp = np.zeros_like(T1, dtype=complex) + + return R_exp + + +def BD_librational(n_2l, omega_0, omega_std, tau_lf, tau_p, T1): + T1 = np.asarray(T1, dtype=float) + if n_2l != 0 and omega_0 > 0 and omega_std > 0 and tau_lf > 0: + omega_0n = omega_0 * tau_p + omega_stdn = omega_std * tau_p + tau_lfn = tau_lf / tau_p + + omega_pts = 2 ** 10 + omega = np.linspace(0, 3 * omega_0n, omega_pts) + delta_omega = omega[1] - omega[0] + omega = omega + delta_omega + + T_pts = 2 ** 12 + T2 = np.linspace(np.min(T1), 5 * tau_lfn, T_pts) + # MATLAB meshgrid(T2, omega) gives shape (len(omega), len(T2)). + # Column/row vectors broadcast to exactly that, without + # materialising two full 4096x1024 coordinate grids. + Tl = T2[np.newaxis, :] + omegal = omega[:, np.newaxis] + + g = (np.exp(-(omegal - omega_0n) ** 2 / 2 / omega_stdn ** 2) + - np.exp(-(omegal + omega_0n) ** 2 / 2 / omega_stdn ** 2)) + Hl = heaviside(Tl) + int_l = Hl / omegal * np.sin(Hl * omegal * Tl) * np.exp(-Hl * Tl / tau_lfn) + r_l = _trapz(g * int_l, omega, axis=0) + + C_l = 1 / _trapz(r_l, T2) + R_l = n_2l * C_l * r_l + R_l_interp = np.interp(T1, T2, R_l) + else: + R_l_interp = np.zeros_like(T1) + + return R_l_interp + + +def BD_vibrational(n_2v, w_0v, tau_vf, tau_p, T1): + T1 = np.asarray(T1, dtype=float) + if n_2v != 0 and w_0v > 0 and tau_vf > 0: + w_0vn = w_0v * tau_p + tau_vfn = tau_vf / tau_p + H = heaviside(T1) + r_v = H * np.sin(H * w_0vn * T1) * np.exp(-H * T1 / tau_vfn) + + if np.max(T1) / tau_vfn > 10: + C_v = 1 / _trapz(r_v, T1) + else: + C_v = 1 / (w_0vn / (w_0vn ** 2 + (1 / tau_vfn) ** 2)) + + R_v = n_2v * C_v * r_v + else: + R_v = np.zeros_like(T1) + + return R_v + + +# ============================================================================= +# BD_3_level_triplet.m +# ============================================================================= + +def _solve_population_odes(diff_eq, indata, t0, t1, t_eval): + """One call to the stiff ODE solver, mirroring MATLAB's ode15s + tspan-length behavior (see module docstring).""" + if t_eval is None: + sol = solve_ivp(diff_eq, (t0, t1), indata, method="BDF", + rtol=1e-3, atol=1e-3, dense_output=False) + t_out = sol.t + else: + sol = solve_ivp(diff_eq, (t_eval[0], t_eval[-1]), indata, method="BDF", + rtol=1e-3, atol=1e-3, t_eval=t_eval) + t_out = t_eval + return t_out, sol.y.T # sol.y is (n_states, n_times) -> transpose to (n_times, n_states) + + +# The five populations tracked by the ESA system, in solver order -- +# matches the original's `pop_names` cell array. +POPULATION_NAMES = ["N_S_0", "N_S_1", "N_S_2", "N_T_1", "N_T_2"] + + +def BD_3_level_triplet(alpha_2_e, I_0_e, lambda_e, n_g_e, tau_e, w_0_e, + n_g_p, L, N0, X0, + sigma_S_01, sigma_S_12, sigma_T_12, + tau_ISC, tau_S_10, tau_S_21, tau_TS, tau_T_21, + n_t_in, tau_d, x, y, diagnostics_out=None): + """ + Propagates a 5-level (N_S0,N_S1,N_S2,N_T1,N_T2) excited-state + population system through the sample thickness for a set of + radial excitation-irradiance levels, then propagates the probe + transmission through the same populations, and finally maps the + result onto the (x, y, tau_d) grid as a Gaussian excitation + profile in x/y. Returns a_ESA with shape (len(y), len(x), + n_t_in, len(tau_d)) -- see module docstring on axis order. + + n_t_in: pass an int for the number of time-axis repeats (this is + all the original code actually used from its `t_in` argument -- + its values were never otherwise read). + + diagnostics_out: pass a dict to have the intermediate population + and irradiance arrays stored in it, for the diagnostic plots the + original drew under `if diagnostics`. The return value is + unaffected, so callers that do not want them are unchanged. + """ + _diag_on = diagnostics_out is not None + _t_start = time.time() + if _diag_on: + _diag_print("BD_3_level_triplet - Calculating excited state effects.") + + v_e = c / n_g_e # pump group velocity [m/s] + v_p = c / n_g_p # probe group velocity [m/s] + E_photon = (h * c) / lambda_e + + z_steps = 50 + irr_pts = 10 + + indata0 = np.zeros(5) + indata0[0] = N0 + + z = np.linspace(0, L, z_steps) + delta_z = z[1] - z[0] + + t_min = np.min(tau_d) + t_max = np.max(tau_d) + t0 = min(-3 * tau_e, t_min) + t1 = t_max + + rad_fac = np.linspace(1, 0, irr_pts) + delay_points = len(tau_d) + + I_p = np.ones((delay_points, z_steps, irr_pts)) + + I_0_e_norm = I_0_e * np.tile(rad_fac, (len(z), 1)) # (z_steps, irr_pts) + I_0_e_arr = I_0_e_norm.copy() + + t_grid = None # fixed time grid, established on the first solve + Y_out = None + zero_ind = None + + for l in range(irr_pts): + for i in range(len(z) - 1): + + def diff_eq(t, yv, _i=i, _l=l): + return excite_prop(t, yv, z[_i], I_0_e_arr[_i, _l], v_e, v_p, tau_e, + E_photon, sigma_S_01, sigma_S_12, sigma_T_12, + tau_ISC, tau_S_10, tau_S_21, tau_TS, tau_T_21, alpha_2_e) + + t_out, Y = _solve_population_odes(diff_eq, indata0, t0, t1, t_grid) + + if t_grid is None: + t_grid = t_out # fixed grid, reused (unchanged) from here on + Y_out = np.zeros((len(t_grid), len(z), 5, irr_pts)) + zero_ind = int(np.argmin(np.abs(t_grid))) + + Y_out[:, i, :, l] = Y + + I_0_e_arr[i + 1, l] = I_0_e_arr[i, l] - ( + sigma_S_01 * Y[zero_ind, 0] + sigma_S_12 * Y[zero_ind, 1] + + sigma_T_12 * Y[zero_ind, 3] + alpha_2_e * I_0_e_arr[i, l] + ) * I_0_e_arr[i, l] * delta_z + + # interpolate from the internal t_grid onto the requested tau_d + # delays (the z/state/irr_pts axes are unchanged, so this reduces + # to a 1D interpolation along the time axis) + Y_interp = interp1d(t_grid, Y_out, axis=0, kind="linear", + bounds_error=False, fill_value="extrapolate")(tau_d) + # Y_interp shape: (delay_points, z_steps, 5, irr_pts) + + # propagate the probe through the sample + for j in range(len(z) - 1): + absorb = (sigma_S_01 * Y_interp[:, j, 0, :] + sigma_S_12 * Y_interp[:, j, 1, :] + + sigma_T_12 * Y_interp[:, j, 3, :]) + I_p[:, j + 1, :] = I_p[:, j, :] - (absorb + alpha_2_e * I_p[:, j, :]) * I_p[:, j, :] * delta_z + + I_p_end = I_p[:, -1, :] # (delay_points, irr_pts) + + # 2D interpolant over (tau_d, excitation-irradiance fraction) + rad_fac_incr = rad_fac[::-1] # increasing order + I_p_end_incr = I_p_end[:, ::-1] # matching column flip + F = RegularGridInterpolator((tau_d, rad_fac_incr), I_p_end_incr, + method="linear", bounds_error=False, fill_value=None) + + a_ESA = _build_esa_time_grid(F, x, y, tau_d, w_0_e, X0, n_t_in) + + if diagnostics_out is not None: + # Everything the original's `if diagnostics` block plotted: + # the five population surfaces vs. normalized delay and depth, + # the excitation transmission vs. depth, and the probe + # transmission vs. delay -- one trace per radial irradiance + # factor for the latter two. + diagnostics_out.update( + pop_names=POPULATION_NAMES, + Y_interp=Y_interp, N0=N0, + z=z, L=L, tau_d=tau_d, tau_e=tau_e, + rad_fac=rad_fac, + I_0_e_arr=I_0_e_arr, I_0_e_norm=I_0_e_norm, + I_p_end=I_p_end, + ) + _diag_print("BD_3_level_triplet - Calculation time: " + f"{time.time() - _t_start:g} s.") + + return a_ESA + + +def _build_esa_time_grid(F, x, y, tau_d, w_0_e, X0, n_t_in): + """Builds a_ESA with shape (len(y), len(x), n_t_in, len(tau_d)). + + Reproduces the net numerical result of the original MATLAB code's + meshgrid(x,y,tau_d) + index-by-m loop (see module docstring) -- + the excitation-irradiance profile is a Gaussian in x (offset by + X0*w_0_e) and y, and the probe transmission is looked up from F + at (tau_d, that irradiance fraction) for every (y, x) location. + """ + X_mesh, Y_mesh = np.meshgrid(x, y) # shape (len(y), len(x)) + I_e_grid_2d = np.exp(-((X_mesh - w_0_e * X0) ** 2 + Y_mesh ** 2) / w_0_e ** 2) + + # One interpolator call over the whole (y, x, tau_d) block instead + # of one per delay point. + shape = I_e_grid_2d.shape + tau_d.shape + pts = np.stack([np.broadcast_to(tau_d, shape), + np.broadcast_to(I_e_grid_2d[..., np.newaxis], shape)], axis=-1) + T_grid = F(pts) + + a_ESA = np.broadcast_to( + T_grid[:, :, np.newaxis, :], (len(y), len(x), n_t_in, len(tau_d)) + ).copy() + return a_ESA + + +# ============================================================================= +# BD_Fresnel_func_ni.m +# ============================================================================= + +def BD_Fresnel_func_ni(params: BDFresnelParams): + """ + Main entry point: calculates the beam-deflection cross-correlation + signal (DeltaE/E vs. delay) for the given parameters and selected + mechanisms. + + Returns a dict with keys: T (normalized transmission-like total + energy, for reference), tau_d (delay axis, fs), DeltaEoE (the beam + deflection signal), Delta_n (equivalent nonlinear index change). + """ + _t_start = time.time() + + # --- parse input parameters (convert to SI) --- + lambda_p = params.lambda_p * 1e-9 + tau_p = params.tau_p * 1e-15 + w_0_p = params.w_0p * 1e-6 + + lambda_ = params.lambda_ * 1e-9 + tau = params.tau * 1e-15 + w_0 = params.w_0 * 1e-6 + + d = params.d * 1e-2 + X0 = params.x_0 + + L = params.l * 1e-3 + + alpha = params.alpha * 100 + alpha_2d = params.alpha_2d * 1e-11 + + sigma_p = params.sigma_p + I_0_p = params.I_0_p + + ng_p = params.ng_p + ng = params.ng + + rho = params.rho + + X_max, X_num = params.X_max, params.X_num + T_min, T_max, T_num = params.T_min, params.T_max, params.T_num + T_d_min, T_d_max, T_d_num = params.T_d_min, params.T_d_max, params.T_d_num + + # --- calculated parameters --- + sigma = alpha * L / 2 + + t = tau / tau_p + W_0_p = w_0_p / w_0 + D = d / w_0 + LAMBDA = lambda_ / w_0 + K_0 = 2 * np.pi / LAMBDA + + dX = abs(2 * X_max / X_num) + dT = 2 * abs(T_max + abs(rho)) / T_num + + # --- initialization --- + X_vec = np.arange(-X_max, X_max + dX / 2, dX) + Y_vec = np.arange(-X_max, X_max + dX / 2, dX) + + if rho > 0: + T_L = T_min + float(heaviside(np.array(-rho))) * rho + T_U = T_max + float(heaviside(np.array(rho))) * rho + else: + T_L, T_U = T_min, T_max + + T_vec = np.arange(T_L, T_U + dT / 2, dT) + # T_d_vec uses linspace (rather than the arange+tolerance pattern + # used for X_vec/T_vec/T1 above, or the original's T_d_min:dT_d:T_d_max, + # which is why no dT_d step is computed here) so its endpoints land + # exactly on T_d_min/T_d_max with no floating-point overshoot -- + # T_d_min/T_d_max are set by the GUI to match the imported data's + # delay range exactly, so the simulated tau_d output must never + # extend past that range. + T_d_vec = np.linspace(T_d_min, T_d_max, T_d_num + 1) + + # ndgrid(Y,X,T,T_d): axis order preserved exactly (axis0=Y, axis1=X, + # axis2=T, axis3=T_d) -- see module docstring. + # + # sparse=True returns broadcastable (nY,1,1,1), (1,nX,1,1), + # (1,1,nT,1), (1,1,1,nTd) views instead of four dense 4D arrays. + # Every expression below is elementwise, so numpy broadcasts them + # to identical results -- but on the default grid the dense form + # spends ~1.7 GB and a second of copying just to store coordinates. + Y, X, T, T_d = np.meshgrid(Y_vec, X_vec, T_vec, T_d_vec, + indexing="ij", sparse=True) + n_T, n_T_d = len(T_vec), len(T_d_vec) + + a_p_0 = np.exp(-((X + X0 * W_0_p) ** 2 + Y ** 2) / W_0_p ** 2) + sigma_p2 = I_0_p * a_p_0 * alpha_2d * L / 2 + + T_fac = 5 + T1_max = T_d_max + 2 * T_fac + abs(rho) + T1_min = -T1_max + T1_num = 2 ** 14 - 1 + dT1 = abs(T1_max - T1_min) / T1_num + T1 = np.arange(T1_min, T1_max + dT1 / 2, dT1) + + n_responses = len(params.mech) + R_n = np.zeros((n_responses, len(T1)), dtype=complex) + # Additive and multiplicative identities: kept scalar so that a run + # with no electronic/ESA mechanism never allocates a 4D array for + # them. Both broadcast exactly as the dense zeros/ones did. + I_RESP = 0.0 + a_ESA = 1.0 + have_electronic = False + n_2e = alpha_2e = 0.0 + + rho_min = 1e-4 + # Per-mechanism response-function plots. The original drew these + # from inside BD_exp_rise_decay / BD_librational / BD_vibrational, + # each of which plotted exactly the array it returned -- so they + # are collected here from R_n instead, which keeps the response + # functions themselves free of display code. Titles and axis + # labels are the ones the original passed at each call site; the + # real (refractive) part is plotted when n_2 is nonzero and the + # imaginary (absorptive) part when alpha_2 is nonzero, matching + # BD_exp_rise_decay's two `if` guards. + diag_responses = [] + esa_diag = {} if params.diagnostics else None + + def _record(idx, refraction=False, absorption=False): + """Notes that mechanism `idx` should appear in the refractive + and/or absorptive panel of the raw-response figure. The original + drew a refraction plot when n_2 was nonzero and an absorption + plot when alpha_2 was nonzero, which is what these flags carry. + + `number` is the 1-based mechanism slot, the same numbering the + parameter log uses ("Mechanism 1:", "Mechanism 2:", ...), so a + diagnostic plot can be traced back to the row that produced it. + """ + if not params.diagnostics: + return + diag_responses.append(dict(index=idx, number=idx + 1, + mech_name=params.mech[idx].name, + refraction=refraction, absorption=absorption)) + + for i, mech in enumerate(params.mech): + p = mech.param + name = mech.name + + if name == "None (both)": + pass + + elif name == "Electronic (both)": + have_electronic = True + alpha_2e = p[0] * 1e-11 + n_2e = p[1] * 1e-19 + + if rho < rho_min and sigma_p == 0: + I_RESP = I_0_p * (2 * n_2e + 1j * alpha_2e) * np.exp(-(T + T_d) ** 2) * (-1 + sigma_p2) + + elif rho < rho_min and sigma_p != 0: + A1 = np.exp(-2 * sigma_p - (T + T_d) ** 2) + A2 = sigma_p - sigma_p2 + sigma_p / np.tanh(sigma_p) + A3 = np.sinh(sigma_p) ** 2 + I_RESP = I_0_p * (2 * n_2e + 1j * alpha_2e) * (A1 * A2 * A3) / (2 * sigma_p ** 2) + + elif rho != 0 and sigma_p == 0: + A1 = 2 * np.exp(-rho ** 2 - (T + T_d) ** 2) + A2 = sigma_p2 * (np.exp(rho ** 2) - np.exp(2 * rho * (T + T_d))) + A3 = rho * (-1 + 2 * sigma_p2) - 2 * sigma_p2 * (T + T_d) + A4 = erf(rho - (T + T_d)) + erf(T + T_d) + I_RESP = I_0_p * (2 * n_2e + 1j * alpha_2e) * ((A1 * A2) - (A3 * A4) * np.sqrt(np.pi)) / (2 * rho ** 2) + + elif rho != 0 and sigma_p != 0: + A1 = np.exp((sigma_p * (sigma_p + 2 * rho * (-rho + (T + T_d)))) / rho ** 2) * (sigma_p - sigma_p2) + A2 = erf(rho - (sigma_p / rho) - (T + T_d)) + erf((sigma_p / rho) + (T + T_d)) + A3 = np.exp((4 * sigma_p * (sigma_p + rho * (-rho + (T + T_d)))) / rho ** 2) * sigma_p2 + A4 = erf(rho - 2 * (sigma_p / rho) - (T + T_d)) + erf(2 * (sigma_p / rho) + (T + T_d)) + I_RESP = I_0_p * (2 * n_2e + 1j * alpha_2e) * ((A1 * A2) + (A3 * A4)) * np.sqrt(np.pi) / (2 * rho * sigma_p) + + elif name == "Collisional (NLR)": + n_2c = p[0] * 1e-19 + tau_cr = p[1] * 1e-15 + tau_cf = p[2] * 1e-15 + R_n[i, :] = BD_exp_rise_decay(0, n_2c, tau_cr, tau_cf, tau_p, T1) + _record(i, refraction=n_2c != 0) + + elif name == "Librational (NLR)": + n_2l = p[0] * 1e-19 + omega_0 = p[1] * 1e12 + omega_std = p[2] * 1e12 + tau_lf = p[3] * 1e-15 + R_n[i, :] = BD_librational(n_2l, omega_0, omega_std, tau_lf, tau_p, T1) + # BD_librational plotted unconditionally, even for a + # response that came back as all zeros. + _record(i, refraction=True) + + elif name == "Reorientational (NLR)": + n_2d_ = p[0] * 1e-19 + tau_rr = p[1] * 1e-15 + tau_rf = p[2] * 1e-15 + R_n[i, :] = BD_exp_rise_decay(0, n_2d_, tau_rr, tau_rf, tau_p, T1) + _record(i, refraction=n_2d_ != 0) + + elif name == "Vibrational (NLR)": + n_2v = p[0] * 1e-19 + w_0v = p[1] * 1e12 + tau_vf = p[2] * 1e-12 + R_n[i, :] = BD_vibrational(n_2v, w_0v, tau_vf, tau_p, T1) + _record(i, refraction=True) + + elif name == "ESA - 3 level + triplet (both)": + alpha_2_e = p[0] * 1e-11 + N0 = p[1] * 1e22 + sigma_S_01 = p[2] * 1e-21 + sigma_S_12 = p[3] * 1e-21 + sigma_T_12 = p[4] * 1e-19 # NOTE: original GUI label says "e-21 m^2" but + # BD_Fresnel_func_ni.m actually scales by 1e-19 -- + # preserved verbatim from the source. + tau_S_10 = p[5] * 1e-12 + tau_S_21 = p[6] * 1e-12 + tau_ISC = p[7] * 1e-12 + tau_T_21 = p[8] * 1e-12 + tau_TS = p[9] * 1e-12 + + a_ESA = BD_3_level_triplet( + alpha_2_e, I_0_p, lambda_p, ng_p, tau_p, w_0_p, + ng, L, N0, X0, + sigma_S_01, sigma_S_12, sigma_T_12, + tau_ISC, tau_S_10, tau_S_21, tau_TS, tau_T_21, + n_T, T_d_vec * tau_p, X_vec * w_0, Y_vec * w_0, + diagnostics_out=esa_diag, + ) + if esa_diag is not None: + esa_diag["number"] = i + 1 + + elif name == "Exponential rise/decay (NLA)": + alpha_2exp = p[0] * 1e-11 + tau_expr = p[1] * 1e-15 + tau_expf = p[2] * 1e-15 + R_n[i, :] = BD_exp_rise_decay(alpha_2exp, 0, tau_expr, tau_expf, tau_p, T1) + _record(i, absorption=alpha_2exp != 0) + + elif name == "Exponential rise/decay (NLR)": + n_2exp = p[0] * 1e-19 + tau_expr = p[1] * 1e-15 + tau_expf = p[2] * 1e-15 + R_n[i, :] = BD_exp_rise_decay(0, n_2exp, tau_expr, tau_expf, tau_p, T1) + _record(i, refraction=n_2exp != 0) + + elif name == "Exponential rise/decay (both)": + alpha_2exp = p[0] * 1e-11 + n_2exp = p[1] * 1e-19 + tau_expr = p[2] * 1e-15 + tau_expf = p[3] * 1e-15 + R_n[i, :] = BD_exp_rise_decay(alpha_2exp, n_2exp, tau_expr, tau_expf, tau_p, T1) + _record(i, refraction=n_2exp != 0, absorption=alpha_2exp != 0) + + # --- index change due to non-instantaneous response functions --- + is_resp = np.flatnonzero(np.sum(R_n, axis=1)) + NI_RESP = np.zeros((n_T, n_T_d), dtype=complex) + NI_resp_diag = None + + if is_resp.size > 0: + R_n_active = R_n[is_resp, :] + + I_p_pulse = I_0_p * np.exp(-T1 ** 2) + if np.allclose(I_p_pulse, 0): + I_p_pulse = np.zeros_like(T1) + I_p_pulse[T1_num // 2] = 1 + + NI_resp = np.zeros_like(R_n_active) + for i in range(R_n_active.shape[0]): + # scipy.signal.fftconvolve (FFT-based, O(N log N)) instead of + # numpy.convolve (direct method, O(N^2)) -- ~4x faster here + # for the T1-length (2^14-1 point) arrays involved, with + # results matching to numerical precision (~1e-12). + NI_resp[i, :] = fftconvolve(R_n_active[i, :], I_p_pulse, mode="same") * dT1 + + upp_base = T_vec[:, np.newaxis] + T_d_vec[np.newaxis, :] + low_base = upp_base - rho + + Resp_tot = np.sum(NI_resp, axis=0) + NI_resp_diag = NI_resp + Resp_tot_interp = interp1d(T1, Resp_tot, kind="linear", + bounds_error=False, fill_value="extrapolate") + + sigma_p20 = I_0_p * alpha_2d * L / 2 + + zoom_pts = 2 ** 8 + att_arr = np.linspace(0, 1, zoom_pts) + + if np.all(sigma_p2 == 0): + atten_fac = np.exp(-2 * sigma_p * att_arr) + else: + B1 = np.exp(-4 * sigma_p * att_arr) + B2 = np.exp(2 * sigma_p * att_arr) * (sigma_p - sigma_p20) + sigma_p20 + atten_fac = np.sqrt((B1 * B2) / sigma_p) + + # Vectorised over the whole (T, T_d) grid rather than looping + # cell by cell: np.linspace broadcasts over array endpoints + # with axis=-1, interp1d maps an ND argument elementwise, and + # trapezoid integrates along the last axis. The per-cell values + # are unchanged -- this is the same arithmetic on the same + # numbers, just issued as whole-array operations instead of + # n_T * n_T_d individual ones. + if rho != 0: + T1_zoomed = np.linspace(low_base, upp_base, zoom_pts, axis=-1) + Resp_tot_zoomed = Resp_tot_interp(T1_zoomed) * atten_fac + NI_RESP = _trapz(Resp_tot_zoomed / rho, T1_zoomed, axis=-1) + else: + NI_RESP = Resp_tot_interp(low_base) + + # --- combine instantaneous and non-instantaneous responses --- + # Left at (1,1,nT,nT_d): it has no x/y dependence, so broadcasting + # it against the field below is equivalent to expanding it here and + # avoids a full 4D temporary when no electronic mechanism is set. + TOT_RESP = I_RESP + NI_RESP[np.newaxis, np.newaxis, :, :] + + eta = (2 * np.pi / lambda_) * L * np.real(TOT_RESP) + Gamma = L * np.imag(TOT_RESP) + CHI_RESP = eta + 1j * Gamma + + # --- propagation to detector --- + spacePart = np.exp(-X ** 2 - Y ** 2) + a_out = (spacePart * np.exp(-sigma - ((-rho + T) ** 2 / t ** 2) / 2 + 1j * (a_p_0 ** 2) * CHI_RESP) * a_ESA) + + # scipy.fft (with workers=-1, using all available CPU cores) instead + # of numpy.fft -- this 2D FFT, batched over the (T, T_d) axes, is + # the single largest cost in the whole calculation for realistic + # grid sizes (multiple seconds), and is embarrassingly parallel + # across those batch dimensions. + # One fftshift over both axes rather than two nested calls: same + # permutation, but it makes a single copy of what can be a + # multi-hundred-MB array instead of two (~10x faster here). + a_det = scipy.fft.fftshift( + scipy.fft.fft2(a_out * np.exp(1j * K_0 / (2 * D) * (X ** 2 + Y ** 2)), + axes=(0, 1), workers=-1), + axes=(0, 1)) + + half = a_det.shape[1] // 2 + a_det.shape[1] % 2 # matches MATLAB's ceil(end/2), 1-indexed + E_left = _trapz(_trapz(_trapz(np.abs(a_det[:, :half, :, :]) ** 2, axis=0), axis=0), axis=0) + E_right = _trapz(_trapz(_trapz(np.abs(a_det[:, half - 1:, :, :]) ** 2, axis=0), axis=0), axis=0) + E_tot = E_left + E_right + + # --- package output --- + T_out = E_tot / E_tot[0] + tau_d_out = T_d_vec * tau_p * 1e15 + DeltaEoE = (E_left - E_right) / E_tot + Delta_n = DeltaEoE / ((2 * np.pi / lambda_) * L * np.sqrt(2 / np.e) * (w_0 / w_0_p) * (2 / np.sqrt(np.pi))) + + result = dict(T=T_out, tau_d=tau_d_out, DeltaEoE=DeltaEoE, Delta_n=Delta_n, + diagnostics=_build_diagnostics( + params, T1, T1_max, R_n, is_resp, NI_resp_diag, + diag_responses, esa_diag, + have_electronic, n_2e, alpha_2e, I_0_p)) + if params.diagnostics: + _diag_print("BD_Fresnel_func - calculation time: " + f"{time.time() - _t_start:g} s.") + return result + + +def _build_diagnostics(params, T1, T1_max, R_n, is_resp, NI_resp_diag, + diag_responses, esa_diag, + have_electronic, n_2e, alpha_2e, I_0_p): + """Packages everything the original's `if params.diagnostics` + blocks plotted, or None when diagnostics are switched off. + + The combined "Response from all mechanisms" figure is built only + when at least one non-instantaneous mechanism is active: the + original guarded it on `exist('NI_resp','var')` and printed a + note instead when there was none, since an instantaneous response + alone has nothing to show against t. + """ + if not params.diagnostics: + return None + + _diag_print("BD_Fresnel_func - generating diagnostic plots.") + diag = dict(T1=T1, T1_max=T1_max, note=None) + + # Per-mechanism response functions, straight from R_n. + responses = [] + for rec in diag_responses: + rec = dict(rec) + rec["R"] = R_n[rec.pop("index"), :] + responses.append(rec) + diag["responses"] = responses + + # Combined figure: every active non-instantaneous response after + # convolution with the pulse, plus the instantaneous response if + # there is one, plus their sum. + if NI_resp_diag is not None: + labels = [f"{i + 1}. {params.mech[i].name}" for i in is_resp] + curves = list(NI_resp_diag) + if have_electronic: + # 2*n_2e, matching what the simulation actually applies (the + # cross-phase-modulation factor of 2: a weak probe sees twice + # the index change a strong pump induces on itself). The + # original MATLAB's diagnostic block used a bare n_2e here + # while its four I_RESP branches all used 2*n_2e, so the + # plotted instantaneous curve was half the value being + # simulated. Corrected here; this is a deliberate divergence + # from the original's output. No factor is applied to + # alpha_2e because the simulation applies none either. + curves.append((2 * n_2e + 1j * alpha_2e) * I_0_p * np.exp(-T1 ** 2)) + electronic = next((k for k, m in enumerate(params.mech) + if m.name.startswith("Electronic")), None) + labels.append(f"{electronic + 1}. {params.mech[electronic].name}" + if electronic is not None else "Electronic") + curves = np.array(curves) + diag["combined"] = dict(labels=labels, curves=curves, + total=np.sum(curves, axis=0)) + else: + diag["combined"] = None + diag["note"] = ("Diagnostic plots are only generated for " + "noninstantaneous responses - no response plots " + "generated.") + + diag["esa"] = esa_diag if esa_diag else None + return diag + + +# ============================================================================= +# calc_beam_params.m (nested function inside BD_Fresnel_GUI.m) +# ============================================================================= + +def _polylog_three_half(z: float) -> float: + """Li_{3/2}(z) for real z, used in the pump transmission formula + below (the original MATLAB relied on a non-built-in `PolyLog` + function not included in the provided sources; this uses mpmath's + polylog, discarding the negligible numerical imaginary part that + can appear for real arguments).""" + return float(mpmath.re(mpmath.polylog(1.5, z))) + + +def calc_beam_params(p: BDFresnelParams) -> BDFresnelParams: + """ + Recomputes the derived beam parameters (tau_p, tau, I_0_p, sigma_p, + ng_p, ng, z_0, z_0_p, Tlin, Tlin_p, rho) from the raw parameters, + mutating and returning `p`. Direct port of calc_beam_params.m + (a nested function inside BD_Fresnel_GUI.m). + + NOTE 1: the original MATLAB function defined a LOCAL speed-of-light + constant here as 299797548 m/s -- a transposed-digit typo versus + the correct 299792458 m/s used everywhere else in the original + codebase (BD_Fresnel_func_ni.m and BD_3_level_triplet.m both had + it right). This port previously reproduced the typo for fidelity; + it now uses the module-level `c` like everything else. The typo + entered only through the group-velocity walk-off term, so the one + visible effect is `rho`, which shifts by 1.7e-5 relative (at the + default parameters, 0.7094620971 -> 0.7094741427). Fits run before + this correction will differ from later ones by that amount. + + NOTE 2: in the original, `tau_p`/`tau` (the HW1/e values the + physics engine actually consumes) are derived from tau_p_FWHM/ + tau_FWHM inside those two fields' own callbacks rather than inside + calc_beam_params.m itself -- but since those callbacks always call + calc_beam_params.m immediately afterward anyway, consolidating + that derivation into this single function (as done below) produces + identical results while keeping one source of truth. + + NOTE 3: matching the original exactly, changing `l` (thickness) or + `d` (sample-detector distance) does NOT trigger a call to this + function from the corresponding GUI field callbacks -- only + E_p, tau_p_FWHM, w_0p, lambda_p, tau_FWHM, w_0, lambda, R_p, R, + alpha, alpha_p, n, dndl, n_p, dndl_p, and alpha_2d do. Since `l` + feeds sigma_p/Tlin_p/rho here, this means editing sample thickness + alone does not live-refresh those derived display values in the + original app -- preserved as-is; the GUI layer calls this function + from exactly the same set of fields. + """ + E_p = p.E_p * 1e-6 + lambda_p = p.lambda_p * 1e-9 + p.tau_p = p.tau_p_FWHM / (2 * np.sqrt(np.log(2))) # HW1/e of I [fs] + tau_p = p.tau_p * 1e-15 + w_0_p = p.w_0p * 1e-6 + + lambda_ = p.lambda_ * 1e-9 + p.tau = p.tau_FWHM / (2 * np.sqrt(np.log(2))) + w_0 = p.w_0 * 1e-6 + + L = p.l * 1e-3 + + alpha = p.alpha * 100 + n = p.n + dn_dl = p.dndl * 1e6 + + R_p = p.R_p + alpha_p = p.alpha_p * 100 + n_p = p.n_p + dn_dlp = p.dndl_p * 1e6 + alpha_2d = p.alpha_2d * 1e-11 + + I_0_p = 2 * E_p / (np.pi ** 1.5 * w_0_p ** 2 * tau_p) * (1 - R_p) + p.I_0_p = I_0_p + + p.sigma_p = alpha_p * L / 2 + sigma_p = p.sigma_p + + sigma_p2 = I_0_p * alpha_2d * L / 2 + + p.ng_p = n_p - lambda_p * dn_dlp + ng_p = p.ng_p + + p.ng = n - lambda_ * dn_dl + ng = p.ng + + p.z_0 = np.pi * w_0 ** 2 / lambda_ + p.z_0_p = np.pi * w_0_p ** 2 / lambda_p + + p.Tlin = np.exp(-alpha * L) + + if sigma_p2 == 0: + p.Tlin_p = (1 - R_p) * np.exp(-2 * sigma_p) + elif sigma_p == 0 and sigma_p2 != 0: + p.Tlin_p = (1 - R_p) * (-_polylog_three_half(-2 * sigma_p2) / (2 * sigma_p2)) + else: + A1 = -1 + np.exp(2 * sigma_p) + p.Tlin_p = (1 - R_p) * ( + -sigma_p * _polylog_three_half(-(A1 * np.exp(-2 * sigma_p) * sigma_p2) / sigma_p) + / (A1 * sigma_p2) + ) + + p.rho = L / (tau_p * c) * (ng - ng_p) + + return p + + +# ============================================================================= +# inputs_valid.m (nested function inside BD_Fresnel_GUI.m) +# ============================================================================= + +def inputs_valid(p: BDFresnelParams) -> bool: + """Direct port of inputs_valid.m: whether the Fit button should be + enabled. Requires physically sensible beam/material parameters AND + that data has actually been imported.""" + return bool( + p.E_p > 0 + and p.tau_p_FWHM > 0 + and p.w_0p > 0 + and p.lambda_p > 0 + and p.tau_FWHM > 0 + and p.w_0 > 0 + and p.lambda_ > 0 + and p.n_p >= 1 + and p.n >= 1 + and 0 <= p.R < 1 + and 0 <= p.R_p < 1 + and p.alpha >= 0 + and p.alpha_p >= 0 + and p.d > 0 + and p.l > 0 + and p.data_imported + ) + + +# ============================================================================= +# save_settings.m / persistence (JSON in place of MATLAB's .mat file) +# ============================================================================= + +def params_to_dict(p: BDFresnelParams) -> dict: + d = dict(p.__dict__) + d["mech"] = [dict(name=m.name, param=list(m.param)) for m in p.mech] + return d + + +def params_from_dict(d: dict) -> BDFresnelParams: + d = dict(d) + mech_list = d.pop("mech", None) + p = BDFresnelParams(**{k: v for k, v in d.items() if k in BDFresnelParams.__dataclass_fields__}) + if mech_list: + p.mech = [Mechanism(name=m["name"], param=list(m["param"])) for m in mech_list] + return p + + +def save_settings(p: BDFresnelParams, filepath: str) -> None: + """JSON equivalent of save_settings.m (which saved handles.params + to last_settings.mat).""" + import json + with open(filepath, "w") as f: + json.dump(params_to_dict(p), f, indent=2) + + +def load_settings(filepath: str) -> BDFresnelParams: + import json + with open(filepath) as f: + d = json.load(f) + return params_from_dict(d) diff --git a/bd_fresnel_gui.py b/bd_fresnel_gui.py new file mode 100644 index 0000000..4727905 --- /dev/null +++ b/bd_fresnel_gui.py @@ -0,0 +1,1675 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +bd_fresnel_gui.py +================== + +Desktop GUI for the beam-deflection Fresnel-propagation fitting +program (bd_fresnel_core.py). Tkinter port of BD_Fresnel_GUI.m / +BD_Fresnel_GUI.fig. + +Lets you: + * Enter pump/probe beam and material parameters + * Select up to 7 simultaneous physical "mechanisms" and set each + one's parameters via the set_params_dialog popup + * Import a transmission/deflection data file + * Run the simulation ("Fit" -- in the original app, and here, this + means "forward-simulate with the current parameters over the + delay range spanned by the imported data," not an automated + least-squares optimizer; you compare the simulated curve to the + data by eye and adjust parameters, exactly as in the original) + * See live Transmission (%) and DeltaE/E (%) vs. delay plots + * Export the fit/data comparison as CSV plus a detailed log file + * Settings persist between sessions (JSON file next to this script, + replacing the original's last_settings.mat) + +Run with: python bd_fresnel_gui.py +""" + +import os +import time +import threading +import traceback +import datetime + +import numpy as np +import tkinter as tk +import tkinter.font as tkfont +from tkinter import ttk, filedialog, messagebox + +from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg + +from bd_fresnel_core import ( + BDFresnelParams, + Mechanism, + MECHANISM_NAMES, + calc_beam_params, + inputs_valid, + BD_Fresnel_func_ni, + save_settings, + load_settings, +) +from set_params_dialog import open_set_params_dialog + +SETTINGS_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "last_settings.json") + +# Fields that (in the original MATLAB app) trigger a recompute of the +# derived beam parameters (calc_beam_params) when edited. Note `l`, +# `d`, `shift`, `x_0` are deliberately excluded -- see the NOTE 3 in +# bd_fresnel_core.calc_beam_params for why (faithfully preserved from +# the original, not a translation gap). +CALC_BEAM_PARAMS_FIELDS = { + "E_p", "tau_p_FWHM", "w_0p", "lambda_p", + "tau_FWHM", "w_0", "lambda_", + "R_p", "R", "alpha", "alpha_p", "n", "dndl", "n_p", "dndl_p", "alpha_2d", +} + +# (field, label, unit, abs_on_entry, log_name) -- mirrors each +# et__Callback in BD_Fresnel_GUI.m. abs_on_entry=True means the +# original applies abs() to the typed value (matching fields whose +# validation message says "greater than 0" AND which are physically +# positive-only quantities); the rest accept signed values (even where +# the log message says ">0", since the original's own numeric +# validation there is permissive -- only NaN is actually rejected at +# entry, faithfully preserved). +PUMP_FIELDS = [ + ("E_p", "E_p (pump energy)", "uJ", True), + ("tau_p_FWHM", "tau_p_FWHM", "fs", True), + ("w_0p", "w_0p (pump waist)", "um", True), + ("lambda_p", "lambda_p (pump)", "nm", True), +] +PROBE_FIELDS = [ + ("tau_FWHM", "tau_FWHM", "fs", True), + ("w_0", "w_0 (probe waist)", "um", True), + ("lambda_", "lambda (probe)", "nm", True), +] +MAT_PUMP_FIELDS = [ + ("R_p", "R_p (reflectivity)", "0-1", True), + ("alpha_p", "alpha_p (absorption)", "cm^-1", True), + ("n_p", "n_p (index)", "", True), + ("dndl_p", "dndl_p (dispersion)", "um^-1", False), + ("alpha_2d", "alpha_2d (2PA)", "e-11 m/W", False), +] +MAT_PROBE_FIELDS = [ + ("R", "R (reflectivity)", "0-1", True), + ("alpha", "alpha (absorption)", "cm^-1", True), + ("n", "n (index)", "", True), + ("dndl", "dndl (dispersion)", "um^-1", False), +] +SYSTEM_FIELDS = [ + ("l", "l (thickness)", "mm", True), + ("d", "d (sample->detector)", "cm", True), + ("shift", "shift (delay zero)", "fs", False), + ("x_0", "x_0 (pump-probe offset)", "w_0p", False), +] + +# Escape sequences accepted in the Delimiter field. A literal tab +# cannot be typed into an Entry (Tab moves focus), so "\t" stands in +# for one; a blank field means "any run of whitespace", which is what +# genfromtxt does when given None. +DELIMITER_ESCAPES = {"\\t": "\t", "\\s": " "} + + +def resolve_delimiter(text: str): + """Turns the Delimiter field's text into the value genfromtxt wants.""" + if not text: + return None # split on any whitespace + return DELIMITER_ESCAPES.get(text, text) + + +def describe_delimiter(text: str) -> str: + """Readable name for the delimiter, for the log and console.""" + if not text: + return "any whitespace" + return {",": "comma", "\t": "tab", " ": "space", ";": "semicolon", + "|": "pipe"}.get(resolve_delimiter(text), f"{text!r}") + + +# The simulation grid, in the order shown in the "Simulation +# parameters" box: (attribute, label, unit, kind). Integer fields are +# counts and must be >= 1; the float fields are extents and cannot be +# negative. T_d_min/T_d_max are deliberately absent -- they are taken +# from the imported scan's delay range, not entered. +SIM_FIELDS = [ + ("X_num", "X_num (spatial pts)", "points", "int"), + ("X_max", "X_max (spatial extent)", "w_0", "float"), + ("T_num", "T_num (time pts)", "points", "int"), + ("T_max", "T_max (time extent)", "tau_p", "float"), + ("T_d_num", "T_d_num (delay pts)", "points", "int"), +] + +# The numeric parameter boxes, in panel order. Each entry is +# (section title, field list); the field tuples are +# (attribute, label, unit, restrict-to-nonnegative). +NUMERIC_FIELD_SECTIONS = [ + ("Pump (Excitation) Beam", PUMP_FIELDS), + ("Probe Beam", PROBE_FIELDS), + ("Material @ Pump Wavelength", MAT_PUMP_FIELDS), + ("Material @ Probe Wavelength", MAT_PROBE_FIELDS), + ("System Geometry", SYSTEM_FIELDS), +] + +# attribute -> restrict-to-nonnegative, flattened once at import rather +# than rebuilt on every field edit. +FIELD_IS_NONNEGATIVE = { + name: nonneg + for _, fields in NUMERIC_FIELD_SECTIONS + for name, _label, _unit, nonneg in fields +} +FIELD_IS_NONNEGATIVE.update( + {name: True for name, _l, _u, kind in SIM_FIELDS if kind == "float"}) + +# Which column of the imported file feeds each quantity. 1-based, in +# the order they are shown in the "Data columns" box. +DATA_COLUMN_FIELDS = [ + ("col_tau_d", "tau_d column"), + ("col_T", "T column"), + ("col_DeltaEoE", "DeltaEoE column"), +] + + +# ----------------------------------------------------------------------- +# Small helper widgets +# ----------------------------------------------------------------------- + +class LabeledEntry(ttk.Frame): + def __init__(self, parent, label, value, width=12, unit="", on_change=None, + integer=False, nonnegative=False): + super().__init__(parent) + ttk.Label(self, text=label, width=20, anchor="w").pack(side="left") + self.var = tk.StringVar(value=str(value)) + entry = ttk.Entry(self, textvariable=self.var, width=width) + entry.pack(side="left") + if integer: + # Refuse anything but digits at the keystroke level, so a + # sign, decimal point or letter can never be typed in the + # first place. The empty string has to stay allowed or the + # field could never be cleared to retype it; the value is + # range-checked (>= 1) when editing finishes. + entry.configure(validate="key", + validatecommand=(self.register(self._digits_only), "%P")) + elif nonnegative: + entry.configure(validate="key", + validatecommand=(self.register(self._no_negative_sign), "%P")) + if unit: + ttk.Label(self, text=unit, foreground="#666", width=9, anchor="w").pack(side="left", padx=(4, 0)) + if on_change is not None: + entry.bind("", lambda e: on_change()) + entry.bind("", lambda e: on_change()) + + @staticmethod + def _digits_only(proposed: str) -> bool: + # str.isdigit() accepts non-ASCII digits and superscripts, which + # int() then rejects, so test the ASCII digits explicitly. + return proposed == "" or all(c in "0123456789" for c in proposed) + + @staticmethod + def _no_negative_sign(proposed: str) -> bool: + """Blocks a minus that would make the value negative, while + still allowing the one inside an exponent -- otherwise a + perfectly good entry like 1e-5 could not be typed.""" + return not any(c == "-" and not (i > 0 and proposed[i - 1] in "eE") + for i, c in enumerate(proposed)) + + def get(self) -> float: + return float(self.var.get()) + + def get_str(self) -> str: + """Raw text, for fields that are not numbers.""" + return self.var.get() + + def get_int(self) -> int: + """Parses a strictly positive integer, raising ValueError on + anything else (including a blank field or a value of 0).""" + value = int(self.var.get()) + if value < 1: + raise ValueError("column numbers start at 1") + return value + + def set(self, value): + self.var.set(str(value)) + + +class LabeledStatic(ttk.Frame): + """Read-only calculated-value display (e.g. rho, I_0_p).""" + + def __init__(self, parent, label): + super().__init__(parent) + ttk.Label(self, text=label, width=20, anchor="w").pack(side="left") + self.var = tk.StringVar(value="--") + ttk.Label(self, textvariable=self.var, width=16, anchor="w", + foreground="black").pack(side="left") + + def set(self, value): + self.var.set(value) + + +class MechanismRow(ttk.Frame): + def __init__(self, parent, index, on_change): + super().__init__(parent) + self.index = index + self.on_change = on_change + ttk.Label(self, text=f"Mech {index + 1}:", width=9, anchor="w").pack(side="left") + self.mech_var = tk.StringVar(value=MECHANISM_NAMES[0]) + combo = ttk.Combobox(self, textvariable=self.mech_var, values=MECHANISM_NAMES, + state="readonly", width=26) + combo.pack(side="left", padx=(0, 4)) + combo.bind("<>", self._on_selected) + ttk.Button(self, text="Params...", width=9, command=self._on_params_button).pack(side="left") + + def _on_selected(self, event=None): + self.on_change(self.index, self.mech_var.get(), reopen_dialog=True) + + def _on_params_button(self): + self.on_change(self.index, self.mech_var.get(), reopen_dialog=True) + + def set_name(self, name): + self.mech_var.set(name) + + +def add_section(parent, title): + frame = ttk.LabelFrame(parent, text=title, padding=8) + frame.pack(fill="x", padx=8, pady=6) + return frame + + +class ResizableFigureCanvas: + """Keeps an embedded Matplotlib Figure letterboxed at its original + aspect ratio as its holder frame is resized (see zscan_gui.py for + the same pattern / rationale).""" + + def __init__(self, holder, fig): + self.holder = holder + self.fig = fig + self.aspect = fig.get_figwidth() / fig.get_figheight() + self.dpi = fig.get_dpi() + + self.canvas = FigureCanvasTkAgg(fig, master=holder) + self.widget = self.canvas.get_tk_widget() + self.widget.place(x=0, y=0) + + holder.bind("", self._resize) + holder.update_idletasks() + self._resize() + + def _resize(self, event=None): + if event is not None: + w, h = event.width, event.height + else: + w, h = self.holder.winfo_width(), self.holder.winfo_height() + if w < 2 or h < 2: + return + + if w / h > self.aspect: + new_h = h + new_w = int(round(h * self.aspect)) + else: + new_w = w + new_h = int(round(w / self.aspect)) + new_w, new_h = max(new_w, 10), max(new_h, 10) + + x, y = (w - new_w) // 2, (h - new_h) // 2 + self.widget.place(x=x, y=y, width=new_w, height=new_h) + + self.fig.set_size_inches(new_w / self.dpi, new_h / self.dpi, forward=False) + relayout = getattr(self.fig, "_bd_relayout", None) + if relayout is not None: + relayout() + self.canvas.draw_idle() + + +# ----------------------------------------------------------------------- +# Main application +# ----------------------------------------------------------------------- + +class BDFresnelApp(tk.Tk): + PREFERRED_FONT_FAMILIES = ("Liberation Sans", "DejaVu Sans", "Noto Sans", "Arial", "Helvetica") + FONT_SIZE = 10 + + def __init__(self): + super().__init__() + self.title("Beam Deflection Fresnel Fit") + self.geometry("1300x860") + self._configure_fonts() + + self.params = self._load_or_default_params() + self.data = None # dict with tau_d, tau_d_shifted, T, DeltaEoE, Delta_n + self.fit = None # dict, output of BD_Fresnel_func_ni + + self._mechanism_rows = [] + self._build_layout() + self._refresh_param_fields_from_state() + self._recalc_beam_params(refresh_display=True) + # Nothing imported and nothing fitted yet, so this leaves both + # Fit and Export disabled on a fresh launch -- including when + # last_settings.json restores a previous session's parameters, + # since the data file itself is not restored with them. + self._update_action_buttons() + + # ------------------------------------------------------------------ + # Fonts (same approach as zscan_gui.py) + # ------------------------------------------------------------------ + + def _configure_fonts(self): + available = set(tkfont.families(self)) + available_lower = {f.lower(): f for f in available} + chosen = None + for preferred in self.PREFERRED_FONT_FAMILIES: + if preferred.lower() in available_lower: + chosen = available_lower[preferred.lower()] + break + if chosen is None: + chosen = "TkDefaultFont" + self.ui_font = (chosen, self.FONT_SIZE) + for name in ("TkDefaultFont", "TkTextFont", "TkFixedFont", "TkMenuFont", + "TkHeadingFont", "TkCaptionFont", "TkSmallCaptionFont", + "TkIconFont", "TkTooltipFont"): + try: + tkfont.nametofont(name).configure(family=chosen, size=self.FONT_SIZE) + except tk.TclError: + pass + self.option_add("*Font", self.ui_font) + ttk.Style(self).configure(".", font=self.ui_font) + + # ------------------------------------------------------------------ + # Settings persistence + # ------------------------------------------------------------------ + + def _load_or_default_params(self) -> BDFresnelParams: + if os.path.isfile(SETTINGS_PATH): + try: + p = load_settings(SETTINGS_PATH) + print(f"bd_fresnel_gui: previous settings loaded from {SETTINGS_PATH}.") + if not (p.pathname and os.path.isfile(os.path.join(p.pathname, p.filename))): + p.filename = "" + p.pathname = "" + return p + except Exception as exc: + print(f"bd_fresnel_gui: could not load {SETTINGS_PATH} ({exc}); using defaults.") + return BDFresnelParams() + + def _save_settings(self): + try: + save_settings(self.params, SETTINGS_PATH) + except Exception as exc: + print(f"bd_fresnel_gui: failed to save settings: {exc}") + + # ------------------------------------------------------------------ + # Layout + # ------------------------------------------------------------------ + + def _build_layout(self): + outer = ttk.PanedWindow(self, orient="horizontal") + outer.pack(fill="both", expand=True) + + left_container = ttk.Frame(outer, width=400) + outer.add(left_container, weight=0) + + canvas = tk.Canvas(left_container, borderwidth=0, highlightthickness=0) + scrollbar = ttk.Scrollbar(left_container, orient="vertical", command=canvas.yview) + self.param_frame = ttk.Frame(canvas) + self.param_frame.bind("", lambda e: canvas.configure(scrollregion=canvas.bbox("all"))) + canvas.create_window((0, 0), window=self.param_frame, anchor="nw") + canvas.configure(yscrollcommand=scrollbar.set) + canvas.pack(side="left", fill="both", expand=True) + scrollbar.pack(side="right", fill="y") + + self._build_param_fields(self.param_frame) + + right = ttk.Frame(outer) + outer.add(right, weight=1) + + # top toolbar: import/fit/export/exit + filename + toolbar = ttk.Frame(right) + toolbar.pack(fill="x", padx=6, pady=6) + self.import_button = ttk.Button(toolbar, text="Import...", command=self._on_import) + self.import_button.pack(side="left") + self.fit_button = ttk.Button(toolbar, text="Fit", command=self._on_fit, state="disabled") + self.fit_button.pack(side="left", padx=4) + self.export_button = ttk.Button(toolbar, text="Export...", command=self._on_export, state="disabled") + self.export_button.pack(side="left") + ttk.Button(toolbar, text="Exit", command=self._on_exit).pack(side="left", padx=4) + self.filename_var = tk.StringVar(value="(no file imported)") + ttk.Label(toolbar, textvariable=self.filename_var, foreground="#444").pack(side="left", padx=(16, 0)) + + self.notebook = ttk.Notebook(right) + self.notebook.pack(fill="both", expand=True, padx=6, pady=(0, 6)) + + # A single tab holds both plots side by side (Transmission on + # the left, Deflection on the right), rather than the original + # app's two separate one-plot tabs. + self.tab_plots = ttk.Frame(self.notebook) + self.tab_diag = ttk.Frame(self.notebook) + self.tab_log = ttk.Frame(self.notebook) + self.notebook.add(self.tab_plots, text="Fitting") + self.notebook.add(self.tab_diag, text="Diagnostics") + self.notebook.add(self.tab_log, text="Parameter log") + + self.plot_holder = ttk.Frame(self.tab_plots) + self.plot_holder.pack(fill="both", expand=True) + + # The diagnostics tab can hold a dozen or more figures (five + # ESA population surfaces alone), so it scrolls rather than + # letterboxing everything into one view. + diag_canvas = tk.Canvas(self.tab_diag, borderwidth=0, highlightthickness=0) + diag_scroll = ttk.Scrollbar(self.tab_diag, orient="vertical", + command=diag_canvas.yview) + self.diag_holder = ttk.Frame(diag_canvas) + self.diag_holder.bind( + "", + lambda e: diag_canvas.configure(scrollregion=diag_canvas.bbox("all"))) + diag_canvas.create_window((0, 0), window=self.diag_holder, anchor="nw") + diag_canvas.configure(yscrollcommand=diag_scroll.set) + diag_canvas.pack(side="left", fill="both", expand=True) + diag_scroll.pack(side="right", fill="y") + + self.log_text = tk.Text(self.tab_log, wrap="word", font=self.ui_font) + self.log_text.pack(fill="both", expand=True, padx=6, pady=6) + + status_bar = ttk.Frame(right) + status_bar.pack(fill="x", padx=6, pady=(0, 6)) + self.status_var = tk.StringVar(value="Ready.") + ttk.Label(status_bar, textvariable=self.status_var).pack(side="left") + self.progress = ttk.Progressbar(status_bar, mode="indeterminate", length=160) + self.progress.pack(side="right") + + # Both are held only so the embedded canvases (and the resize + # bindings they own) survive garbage collection; nothing reads + # them back. + self._plot_view = None + self._diag_canvases = [] + + def _build_param_fields(self, parent): + self._field_widgets = {} + + sec = add_section(parent, "Data columns") + for name, label in DATA_COLUMN_FIELDS: + w = LabeledEntry(sec, label, getattr(self.params, name), width=6, + integer=True, + on_change=lambda n=name: self._on_column_change(n)) + w.pack(fill="x", pady=2) + self._field_widgets[name] = w + w = LabeledEntry(sec, "Delimiter", self.params.delimiter, width=6, + on_change=self._on_delimiter_change) + w.pack(fill="x", pady=2) + self._field_widgets["delimiter"] = w + + sec = add_section(parent, "Simulation parameters") + for name, label, unit, kind in SIM_FIELDS: + if kind == "int": + w = LabeledEntry(sec, label, getattr(self.params, name), + width=6, unit=unit, integer=True, + on_change=lambda n=name: self._on_int_field_change(n)) + else: + w = LabeledEntry(sec, label, getattr(self.params, name), + width=6, unit=unit, nonnegative=True, + on_change=lambda n=name: self._on_field_change(n)) + w.pack(fill="x", pady=2) + self._field_widgets[name] = w + + for title, fields in NUMERIC_FIELD_SECTIONS: + sec = add_section(parent, title) + for name, label, unit, nonneg in fields: + w = LabeledEntry(sec, label, getattr(self.params, name), unit=unit, + nonnegative=nonneg, + on_change=lambda n=name: self._on_field_change(n)) + w.pack(fill="x", pady=2) + self._field_widgets[name] = w + + sec = add_section(parent, "Mechanisms") + for i in range(self.params.n_mech): + row = MechanismRow(sec, i, self._on_mechanism_change) + row.pack(fill="x", pady=2) + self._mechanism_rows.append(row) + + sec = add_section(parent, "Diagnostics") + self.diagnostics_var = tk.BooleanVar(value=self.params.diagnostics) + ttk.Checkbutton(sec, text="Show diagnostic plots during Fit", + variable=self.diagnostics_var, + command=self._on_diagnostics_change).pack(anchor="w") + + sec = add_section(parent, "Calculated Parameters (probe)") + self.calc_ng = LabeledStatic(sec, "n_g (group index)") + self.calc_ng.pack(fill="x", pady=1) + self.calc_Tlin = LabeledStatic(sec, "T_lin") + self.calc_Tlin.pack(fill="x", pady=1) + self.calc_z0 = LabeledStatic(sec, "z_0 (Rayleigh range)") + self.calc_z0.pack(fill="x", pady=1) + + sec = add_section(parent, "Calculated Parameters (pump)") + self.calc_ngp = LabeledStatic(sec, "n_g (group index)") + self.calc_ngp.pack(fill="x", pady=1) + self.calc_Tlinp = LabeledStatic(sec, "T_lin") + self.calc_Tlinp.pack(fill="x", pady=1) + self.calc_z0p = LabeledStatic(sec, "z_0 (Rayleigh range)") + self.calc_z0p.pack(fill="x", pady=1) + self.calc_I0p = LabeledStatic(sec, "I_0 (peak irradiance)") + self.calc_I0p.pack(fill="x", pady=1) + + sec = add_section(parent, "Other") + self.calc_rho = LabeledStatic(sec, "rho (GVM parameter)") + self.calc_rho.pack(fill="x", pady=1) + + # ------------------------------------------------------------------ + # Field / state synchronization + # ------------------------------------------------------------------ + + def _refresh_param_fields_from_state(self): + for name, widget in self._field_widgets.items(): + widget.set(getattr(self.params, name)) + for i, row in enumerate(self._mechanism_rows): + row.set_name(self.params.mech[i].name) + self.diagnostics_var.set(self.params.diagnostics) + if self.params.filename: + self.filename_var.set(self.params.filename) + + def _on_field_change(self, field_name): + widget = self._field_widgets[field_name] + try: + value = widget.get() + except ValueError: + print(f"bd_fresnel_gui: '{field_name}' must be a real number.") + value = 0.0 + if FIELD_IS_NONNEGATIVE[field_name]: + value = abs(value) + setattr(self.params, field_name, value) + widget.set(value) + print(f"bd_fresnel_gui: {field_name} updated to {value}.") + + if field_name in CALC_BEAM_PARAMS_FIELDS: + self._recalc_beam_params(refresh_display=True) + + if field_name == "shift" and self.data is not None: + self.data["tau_d_shifted"] = self.data["tau_d"] + self.params.shift + self._refresh_plots() + + self._update_fit_button_state() + + def _on_int_field_change(self, field_name, reread=False): + """Shared handler for the positive-integer inputs: the data + column numbers and the simulation grid point counts.""" + widget = self._field_widgets[field_name] + previous = getattr(self.params, field_name) + try: + value = widget.get_int() + except ValueError: + print(f"bd_fresnel_gui: '{field_name}' must be a positive " + f"integer; reverting to {previous}.") + widget.set(previous) + return + + if value == previous: + return + setattr(self.params, field_name, value) + widget.set(value) + print(f"bd_fresnel_gui: {field_name} updated to {value}.") + + if reread and self.params.import_filepath: + self._reload_current_data_file() + self._save_settings() + + def _on_column_change(self, field_name): + # Anything already imported was read with the old column + # layout, so re-read it rather than leaving mislabelled data on + # screen. Re-reading clears the fit for the same reason Import + # does: it belongs to the previous set of columns. + self._on_int_field_change(field_name, reread=True) + + def _on_delimiter_change(self): + widget = self._field_widgets["delimiter"] + previous = self.params.delimiter + value = widget.get_str() + if value == previous: + return + + self.params.delimiter = value + print(f"bd_fresnel_gui: delimiter updated to {value!r} " + f"({describe_delimiter(value)}).") + + # Same reasoning as a column change: whatever is loaded was + # parsed with the old delimiter, so re-read it. + if self.params.import_filepath: + self._reload_current_data_file() + self._save_settings() + + def _reload_current_data_file(self): + path = self.params.import_filepath + try: + data = self._read_data_file(path) + except Exception as exc: + messagebox.showerror("File Import Error", f"File: {path} is invalid.\n\n{exc}") + return + self.data = data + self.params.data_fit = False + self.fit = None + self._refresh_plots() + self._refresh_diagnostics() + self._update_action_buttons() + print(f"bd_fresnel_gui: re-read {path} with the new column layout.") + + def _on_diagnostics_change(self): + self.params.diagnostics = self.diagnostics_var.get() + + def _on_mechanism_change(self, index, mechanism_name, reopen_dialog=False): + previous = self.params.mech[index] + if reopen_dialog: + new_mech = open_set_params_dialog(self, mechanism_name, previous) + if new_mech is not None: + self.params.mech[index] = new_mech + else: + self.params.mech[index] = Mechanism(name=mechanism_name) + self._mechanism_rows[index].set_name(self.params.mech[index].name) + + def _recalc_beam_params(self, refresh_display=False): + calc_beam_params(self.params) + if refresh_display: + self.calc_ng.set(f"{self.params.ng:.3f}") + self.calc_Tlin.set(f"{self.params.Tlin:.3f}") + self.calc_z0.set(f"{self.params.z_0 * 1e3:.3f} mm") + self.calc_ngp.set(f"{self.params.ng_p:.3f}") + self.calc_Tlinp.set(f"{self.params.Tlin_p:.3f}") + self.calc_z0p.set(f"{self.params.z_0_p * 1e3:.3f} mm") + self.calc_I0p.set(f"{self.params.I_0_p * 1e-13:.3f} GW/cm^2") + self.calc_rho.set(f"{self.params.rho:.3f}") + + def _update_fit_button_state(self): + """Fit needs both a data file (it takes its delay range from + the imported scan) and a valid set of beam/material inputs.""" + ready = self.data is not None and inputs_valid(self.params) + self.fit_button.config(state="normal" if ready else "disabled") + + def _update_export_button_state(self): + """Export writes the data/fit comparison table and the plot + image, so it stays disabled until a fit has actually + completed. Importing a new file clears the fit and disables it + again.""" + ready = self.data is not None and self.fit is not None + self.export_button.config(state="normal" if ready else "disabled") + + def _update_action_buttons(self): + self._update_fit_button_state() + self._update_export_button_state() + + # ------------------------------------------------------------------ + # Import + # ------------------------------------------------------------------ + + def _read_data_file(self, path) -> dict: + """Reads the delay/deflection/transmission scan at `path`, + taking each quantity from the column selected in the "Data + columns" box. Raises on a malformed file.""" + raw = np.genfromtxt(path, skip_header=1, + delimiter=resolve_delimiter(self.params.delimiter)) + if raw.ndim == 1: + raw = raw[None, :] + + col_tau_d = self.params.col_tau_d + col_T = self.params.col_T + col_DeltaEoE = self.params.col_DeltaEoE + needed = max(col_tau_d, col_T, col_DeltaEoE) + if raw.shape[1] < needed: + raise ValueError( + f"file has {raw.shape[1]} column(s), but the selected " + f"column numbers need at least {needed}") + if np.isnan(raw).any(): + # A delimiter that does not match the file is the usual + # cause: every line then parses as one unsplittable field + # and comes back as NaN, so say so rather than leaving the + # user to guess at "missing values". + if np.isnan(raw).all(): + raise ValueError( + f"no numeric data found - the delimiter is set to " + f"{describe_delimiter(self.params.delimiter)}, which may " + f"not match this file") + raise ValueError("file must not have missing values") + + # 1-based in the GUI, 0-based into the array. + tau_d = raw[:, col_tau_d - 1] + T = raw[:, col_T - 1] + DeltaEoE = raw[:, col_DeltaEoE - 1] + + lambda_ = self.params.lambda_ * 1e-9 + l = self.params.l * 1e-3 + w_0 = self.params.w_0 * 1e-6 + w_0_p = self.params.w_0p * 1e-6 + k_0 = 2 * np.pi / lambda_ + Delta_n = DeltaEoE / (k_0 * l * np.sqrt(2 / np.e) * (w_0 / w_0_p) * (2 / np.sqrt(np.pi))) + + return dict( + tau_d=tau_d, + tau_d_shifted=tau_d + self.params.shift, + T=T, DeltaEoE=DeltaEoE, Delta_n=Delta_n, + ) + + def _on_import(self): + initial_dir = self.params.pathname or os.getcwd() + path = filedialog.askopenfilename( + title="Import transmission/deflection data", + initialdir=initial_dir, + filetypes=[("Text files", "*.txt"), ("All files", "*.*")], + ) + if not path: + print("bd_fresnel_gui: file import cancelled.") + return + + try: + self.data = self._read_data_file(path) + except Exception as exc: + messagebox.showerror("File Import Error", f"File: {path} is invalid.\n\n{exc}") + return + + self.params.pathname = os.path.dirname(path) + os.sep + self.params.filename = os.path.basename(path) + self.params.import_filepath = path + self.params.data_imported = True + self.params.data_fit = False + self.fit = None + + self._refresh_plots() + self._refresh_diagnostics() + self._update_action_buttons() + self.filename_var.set(self.params.filename) + print(f"bd_fresnel_gui: import of {path} complete.") + self._save_settings() + + # ------------------------------------------------------------------ + # Fit (forward simulation) + # ------------------------------------------------------------------ + + def _on_fit(self): + if self.data is None: + return + self.fit_button.config(state="disabled", text="Processing...") + self.import_button.config(state="disabled") + self.export_button.config(state="disabled") + self.status_var.set("Running simulation...") + self.progress.start(12) + + # Use the shifted delay values (i.e. the same frame the data + # is actually plotted/compared/exported in, tau_d + shift) so + # the simulated fit curve's own delay axis lines up exactly + # with the data it's being compared against. (Note: the + # original MATLAB app derived this from the raw, unshifted + # tau_d instead -- a real frame mismatch whenever shift != 0, + # since refresh_plots.m/pb_Export_Callback.m both compare + # against the shifted values. This is a deliberate correction, + # not a faithfulness gap.) + self.params.T_d_min = float(np.min(self.data["tau_d_shifted"])) / self.params.tau_p + self.params.T_d_max = float(np.max(self.data["tau_d_shifted"])) / self.params.tau_p + # T_d_num is no longer forced here -- it is an input in the + # Simulation Parameters box, defaulting to the 150 this line + # used to hard-code. + + thread = threading.Thread(target=self._fit_worker, daemon=True) + thread.start() + + def _fit_worker(self): + t0 = time.time() + try: + fit = BD_Fresnel_func_ni(self.params) + elapsed = time.time() - t0 + self.after(0, self._on_fit_success, fit, elapsed) + except Exception: + tb = traceback.format_exc() + self.after(0, self._on_fit_error, tb) + + def _on_fit_success(self, fit, elapsed): + self.fit = fit + self.params.data_fit = True + self._refresh_plots() + self._refresh_diagnostics() + + self.log_text.delete("1.0", "end") + self.log_text.insert("1.0", self._build_log_text()) + + self.fit_button.config(text="Fit") + self.import_button.config(state="normal") + self._update_action_buttons() + self.progress.stop() + self.status_var.set(f"Fit complete in {elapsed:.2f} s.") + print(f"bd_fresnel_gui: fitting complete. Elapsed time: {elapsed:.2f} s.") + self._save_settings() + + def _on_fit_error(self, tb_text): + self.fit_button.config(text="Fit") + self.import_button.config(state="normal") + # Export stays available only if an earlier fit succeeded and + # is still on screen; _update_export_button_state decides. + self._update_action_buttons() + self.progress.stop() + self.status_var.set("Error.") + self.log_text.delete("1.0", "end") + self.log_text.insert("1.0", tb_text) + self.notebook.select(self.tab_log) + messagebox.showerror("Fit failed", tb_text.strip().splitlines()[-1]) + + # ------------------------------------------------------------------ + # Plotting + # ------------------------------------------------------------------ + + def _get_plot_context(self): + """Computes the data/fit arrays, axis scale, and shared axis + ranges used by every plot (the two live tabs and the combined + export image), so they all stay perfectly consistent.""" + tau_d = self.data["tau_d"] + tau_d_shifted = self.data["tau_d_shifted"] + n_pts = len(tau_d) + # Base marker size comes from the active rc context (6 pt on + # screen, 3 pt in print), shrinking on dense scans so the + # points stay distinguishable instead of merging into a band. + # The markers are solid dots, so the size can go right down + # without the marker degrading -- there is no ring thickness + # to keep clear of. + import matplotlib + base_marker = matplotlib.rcParams["lines.markersize"] + marker_size = (max(1.0, base_marker * 100 / n_pts) + if n_pts > 100 else base_marker) + + delta_tau_d = abs(np.max(tau_d) - np.min(tau_d)) + if delta_tau_d > 1000 ** 2: + scale, scale_label = 1000 ** 2, "ns" + elif delta_tau_d > 1000: + scale, scale_label = 1000, "ps" + else: + scale, scale_label = 1, "fs" + tau_d_disp = tau_d_shifted / scale + + has_fit = self.fit is not None and self.params.data_fit + if has_fit: + fit_tau_d_disp = self.fit["tau_d"] / scale + T_points = np.concatenate([self.data["T"], self.fit["T"]]) + DeltaEoE_points = np.concatenate([self.data["DeltaEoE"], self.fit["DeltaEoE"]]) + else: + fit_tau_d_disp = None + T_points = self.data["T"] + DeltaEoE_points = self.data["DeltaEoE"] + + # x-axis covers only the data's delay range (matching the + # original MATLAB app's xlim(...) behavior). The fit curve's + # own simulated grid can extend marginally beyond this range + # (floating-point grid construction), but each plotted line + # is given an explicit clip path bound to the axes' patch, so + # any such excess is cleanly cut off at the border rather than + # visibly overflowing it. + x_min, x_max = np.min(tau_d_disp), np.max(tau_d_disp) + + return dict( + tau_d_disp=tau_d_disp, fit_tau_d_disp=fit_tau_d_disp, has_fit=has_fit, + marker_size=marker_size, + T_points=T_points, DeltaEoE_points=DeltaEoE_points, + x_min=x_min, x_max=x_max, scale_label=scale_label, + ) + + # Each panel is drawn in a single colour: red for Transmission, + # blue for Deflection. Data markers and the fit line within one + # panel share that colour and are told apart by their style + # (solid dots vs. a solid line), so the two panels stay + # visually distinct from each other at a glance. + TRANSMISSION_COLOR = "r" + DEFLECTION_COLOR = "b" + + # On-screen the combined figure is drawn large (it gets letterboxed + # into whatever space the window gives it). The exported image is + # built at its true final size instead of being scaled down from + # the screen figure -- 6.5 in wide at 300 dpi, i.e. 1950 px, which + # is a full text-column width on US Letter with 1 in margins. The + # export height keeps the on-screen aspect ratio. + SCREEN_FIGSIZE = (12.0, 5.0) + EXPORT_WIDTH_IN = 6.5 + EXPORT_DPI = 300 + + # Text, marker and line sizes are all specified in points, i.e. in + # absolute physical units, so they do NOT shrink along with the + # figure. The export figure is a little over half the width of the + # on-screen one, so reusing the screen sizes would give it huge + # labels and markers fat enough to merge into a solid band. Each + # context therefore gets its own set, with the print sizes chosen + # to be legible at a 6.5 in column width. + SCREEN_RC = { + "font.size": 10, "axes.titlesize": 14, "axes.labelsize": 10, + "xtick.labelsize": 10, "ytick.labelsize": 10, "legend.fontsize": 10, + "lines.linewidth": 1.5, "lines.markersize": 6, + # Same trimming as the print style below: these pads sit in the + # margin between the axes and the figure edge, so cutting them + # hands the space back to the plots and to the label text. + "axes.labelpad": 2.0, "axes.titlepad": 3.0, + "xtick.major.pad": 2.0, "ytick.major.pad": 2.0, + } + PRINT_RC = { + "font.size": 8, "axes.titlesize": 9, "axes.labelsize": 8, + "xtick.labelsize": 7, "ytick.labelsize": 7, "legend.fontsize": 7, + "lines.linewidth": 1.0, "lines.markersize": 3, + # Tightened from the matplotlib defaults (labelpad 4, tick pad + # 3.5, titlepad 6). Each of these sits in the margin between + # the axes and the figure edge, so trimming them hands the + # space back to the plots without changing the canvas size. + "axes.labelpad": 2.0, "axes.titlepad": 3.0, + "xtick.major.pad": 2.0, "ytick.major.pad": 2.0, + } + + # tight_layout's pad, in multiples of the font size. The 1.08 + # default leaves a wide dead border on every side; 0.25 keeps a + # hairline so nothing touches the edge. Reclaiming that border is + # what pays for the larger on-screen text below. + EXPORT_LAYOUT_PAD = 0.25 + SCREEN_LAYOUT_PAD = 0.25 + + # The on-screen figure is letterboxed into whatever space the + # window gives it, which is usually well under the 12 in it is + # built at. Text is sized in points, so it does not shrink with + # the figure: at a typical window size the labels take up a third + # more of the canvas than the layout allowed for, and run off the + # edge. Scaling the text with the figure keeps the proportions the + # layout was computed for. The floor stops it becoming unreadable + # in a very small window. + MIN_SCREEN_TEXT_SCALE = 0.45 + + # Multiplier on the on-screen text size, paid for by the margin + # space reclaimed above. 1.0 would keep the text proportional to + # the 12 in reference figure; anything higher trades plot area for + # legibility, which is the right trade on screen (unlike the + # export, where the figure is already at its final printed size). + SCREEN_TEXT_BOOST = 1.35 + + def _rescale_screen_text(self, fig, axes): + # Floor applied last, so it is a true minimum: folding the + # boost in afterwards would raise the effective floor and let + # a very small window clip again. + scale = max(fig.get_size_inches()[0] / self.SCREEN_FIGSIZE[0] + * self.SCREEN_TEXT_BOOST, + self.MIN_SCREEN_TEXT_SCALE) + rc = self.SCREEN_RC + for ax in axes: + ax.title.set_fontsize(rc["axes.titlesize"] * scale) + ax.xaxis.label.set_fontsize(rc["axes.labelsize"] * scale) + ax.yaxis.label.set_fontsize(rc["axes.labelsize"] * scale) + # Set through tick_params, not on the label artists: the + # axis rebuilds those on the next draw and would discard a + # size set directly on them. + ax.tick_params(axis="x", labelsize=rc["xtick.labelsize"] * scale) + ax.tick_params(axis="y", labelsize=rc["ytick.labelsize"] * scale) + legend = ax.get_legend() + if legend is not None: + for text in legend.get_texts(): + text.set_fontsize(rc["legend.fontsize"] * scale) + + @staticmethod + def _hide_colliding_boundary_labels(fig, ax_left, ax_right): + """With the panels sharing a spine, the left panel's rightmost + x tick labels can run into the right panel's leftmost ones. + Both panels span the same delay range, so how many collide + depends on the range and the label widths -- a narrow scan + labelled '-0.4', '-0.2', ... crowds the join far more than a + wide one labelled '-2', '0', '2'. Rather than always dropping + the left panel's last tick (too little in the first case, + needlessly lossy in the second), the labels are measured once + laid out and only those actually overlapping are blanked. The + tick marks themselves stay. + + The colliding labels are replaced with empty strings rather + than hidden with set_visible(False): the axis rebuilds its + tick artists on the next draw, which resets their visibility, + so hiding does not survive being redrawn or saved to a file.""" + try: + renderer = fig.canvas.get_renderer() + except AttributeError: + from matplotlib.backends.backend_agg import FigureCanvasAgg + FigureCanvasAgg(fig) + renderer = fig.canvas.get_renderer() + + xlim = ax_left.get_xlim() + fig.draw(renderer) + + # Cache the untouched tick positions/labels the first time, so + # that re-running this on an on-screen resize starts from the + # full set rather than from a previously blanked one. + if not hasattr(ax_left, "_bd_full_ticks"): + ax_left._bd_full_ticks = ( + list(ax_left.get_xticks()), + [t.get_text() for t in ax_left.get_xticklabels()], + ) + locs, labels = ax_left._bd_full_ticks + ax_left.set_xticks(locs, labels=labels) + ax_left.set_xlim(xlim) + fig.draw(renderer) + + lo, hi = min(xlim), max(xlim) + right_boxes = [t.get_window_extent(renderer) + for loc, t in zip(ax_right.get_xticks(), + ax_right.get_xticklabels()) + if t.get_text() and lo <= loc <= hi] + if not right_boxes: + return + + left_texts = list(ax_left.get_xticklabels()) + kept = list(labels) + for i in range(len(left_texts) - 1, -1, -1): + if not labels[i] or not (lo <= locs[i] <= hi): + continue + # A little horizontal padding so labels don't sit flush + # against each other across the join. + box = left_texts[i].get_window_extent(renderer).expanded(1.4, 1.0) + if any(box.overlaps(rb) for rb in right_boxes): + kept[i] = "" + else: + break # labels run left to right; the rest are clear + + if kept != labels: + ax_left.set_xticks(locs, labels=kept) + ax_left.set_xlim(xlim) + + @staticmethod + def _order_legend(ax, data_line, fit_line): + """Legend entries listed as Data over Fit, independent of the + order the artists were drawn in (the fit is plotted first so + the data markers sit on top of it).""" + handles = [data_line] + ([fit_line] if fit_line is not None else []) + ax.legend(handles=handles, labels=[h.get_label() for h in handles], + loc="lower right") + + # The two panels differ only in which signal they draw, its colour, + # and the axis labelling -- everything else (marker style, clipping, + # limits, legend order) is shared, so they are described by a table + # and drawn by one method. + PANELS = { + "T": dict(key="T", color=TRANSMISSION_COLOR, ylabel="T (%)", + title="Transmission", range_key="T_points"), + "DeltaEoE": dict(key="DeltaEoE", color=DEFLECTION_COLOR, + ylabel=r"$\Delta E/E$ (%)", title="Deflection", + range_key="DeltaEoE_points"), + } + + def _plot_signal_axis(self, ax, ctx, which, y_on_right=False): + """Draws one panel: data as solid dots, fit as a solid line of + the same colour, Data listed above Fit in the legend. + + Both series are given an explicit clip path bound to the axes + patch, because the simulated fit grid can extend a hair past + the data's delay range and should be cut off at the border + rather than overflow it. + """ + spec = self.PANELS[which] + key, color = spec["key"], spec["color"] + + fit_line = None + if ctx["has_fit"]: + fit_line, = ax.plot(ctx["fit_tau_d_disp"], 100 * self.fit[key], + linestyle="-", color=color, label="Fit") + fit_line.set_clip_on(True) + fit_line.set_clip_path(ax.patch) + data_line, = ax.plot(ctx["tau_d_disp"], 100 * self.data[key], + linestyle="none", marker="o", color=color, + markeredgewidth=0, + markersize=ctx["marker_size"], label="Data") + data_line.set_clip_path(ax.patch) + + points = ctx[spec["range_key"]] + ax.grid(False) # no major grid lines + ax.set_xlim(ctx["x_min"], ctx["x_max"]) + ax.set_ylim(100 * np.min(points), 100 * np.max(points)) + ax.set_xlabel(rf"$\tau_d$ ({ctx['scale_label']})") + ax.set_ylabel(spec["ylabel"]) + ax.set_title(spec["title"]) # size from rc context + if y_on_right: + ax.yaxis.tick_right() + ax.yaxis.set_label_position("right") + self._order_legend(ax, data_line, fit_line) + + def _refresh_plots(self): + if self.data is None: + return + + fig = self._build_combined_figure() + + for child in self.plot_holder.winfo_children(): + child.destroy() + self._plot_view = ResizableFigureCanvas(self.plot_holder, fig) # held, see __init__ + + def _build_combined_figure(self, figsize=None, print_style=False): + """Builds the single side-by-side figure shown in the plot tab + (and saved as the export image): Transmission on the left, + Deflection on the right with its y-axis and tick labels moved + to the right-hand side. + + `figsize` and `print_style` both default to the on-screen + settings; export passes the smaller print pair. The context is + computed inside the rc context so that the data marker size it + picks scales along with the rest.""" + import matplotlib + from matplotlib.figure import Figure + + with matplotlib.rc_context(self.PRINT_RC if print_style else self.SCREEN_RC): + ctx = self._get_plot_context() + fig = Figure(figsize=figsize or self.SCREEN_FIGSIZE) + ax_left, ax_right = fig.subplots(1, 2) + self._plot_signal_axis(ax_left, ctx, "T") + self._plot_signal_axis(ax_right, ctx, "DeltaEoE", y_on_right=True) + + # The panels butt directly against each other, sharing one + # vertical spine. Nothing has to fit between them: the left + # panel's y-axis is on the left and the right panel's is on + # the right. The x tick labels do collide at the join, + # though, and that is dealt with after layout, once the + # labels have their final positions. + pad = self.EXPORT_LAYOUT_PAD if print_style else self.SCREEN_LAYOUT_PAD + + def relayout(f=fig, a=ax_left, b=ax_right, pad=pad, + print_style=print_style): + # Re-run in full on every on-screen resize. The text is + # rescaled first, then the margins are recomputed for + # the new text size -- doing only one of the two would + # still leave labels clipped or floating. + if not print_style: + self._rescale_screen_text(f, (a, b)) + f.tight_layout(pad=pad) + f.subplots_adjust(wspace=0) + self._hide_colliding_boundary_labels(f, a, b) + + relayout() + fig._bd_relayout = relayout + return fig + + # ------------------------------------------------------------------ + # Diagnostics + # ------------------------------------------------------------------ + + DIAG_FIGSIZE = (7.0, 4.0) + + # Axis labels as matplotlib mathtext, so Greek letters render as + # Greek and sub/superscripts sit where they belong rather than + # showing the literal "tau_p" / "m^2" source. Figure *titles* keep + # their plain-text form: they double as the Tk frame label and the + # export filename, neither of which can render mathtext. + DIAG_LABEL_T = r"$t$ ($\tau_p$)" + DIAG_LABEL_R = r"$R[t]$ (m$^2$/W)" + DIAG_LABEL_A = r"$A[t]$ (m/W)" + DIAG_LABEL_DN = r"$\Delta n$ (unitless)" + DIAG_LABEL_DA = r"$\Delta\alpha$ (m$^{-1}$)" + DIAG_RC = { + "font.size": 9, "axes.titlesize": 11, "axes.labelsize": 9, + "xtick.labelsize": 8, "ytick.labelsize": 8, "legend.fontsize": 7, + "lines.linewidth": 1.2, + } + + @classmethod + def _stacked_figure(cls, n_panels): + """Blank figure sized for `n_panels` stacked vertically.""" + from matplotlib.figure import Figure + + height = cls.DIAG_FIGSIZE[1] * (1.75 if n_panels > 1 else 1.0) + return Figure(figsize=(cls.DIAG_FIGSIZE[0], height)) + + @staticmethod + def _finish_stacked_figure(fig, title, n_panels): + """Lays out a stacked figure. With more than one panel the name + goes in a figure-level title, leaving each panel free to name + the quantity it shows; a lone panel carries the name itself.""" + if n_panels > 1: + fig.suptitle(title) + fig.tight_layout(rect=(0, 0, 1, 0.96)) + else: + fig.axes[0].set_title(title) + fig.tight_layout() + + def _build_diagnostic_figures(self, diag): + """Rebuilds, as a list of (title, Figure), every plot the + original MATLAB drew under `if diagnostics`: + + * "Raw response functions from all mechanisms": every + mechanism's R[t] and A[t] on shared refraction/absorption + panels (from BD_exp_rise_decay / BD_librational / + BD_vibrational, which drew one figure each), + * "Convolved response from all mechanisms": the same + responses after convolution with the pulse, plus their + total (from BD_Fresnel_func_ni), + * the five ESA population surfaces, the excitation + transmission vs. depth and the probe transmission vs. + delay (from BD_3_level_triplet). + """ + import matplotlib + + figures = [] + T1 = diag["T1"] + # The original clipped the summary plot to t = -3 .. T1_max + # rather than the full convolution window; both response + # figures use that range so they can be read against each other. + T_plot_min, T_plot_max = -3.0, diag["T1_max"] + + with matplotlib.rc_context(self.DIAG_RC): + # One figure for every mechanism's response function, laid + # out like the all-mechanisms summary below: the refractive + # parts R[t] share the top panel and the absorptive parts + # A[t] the bottom, one curve per mechanism. A panel is drawn + # only if something lands in it -- a coefficient of zero + # means the original drew nothing for that part. + panels = [ + (np.real, "refraction", "Refraction", self.DIAG_LABEL_R), + (np.imag, "absorption", "Absorption", self.DIAG_LABEL_A), + ] + panels = [panel for panel in panels + if any(r[panel[1]] for r in diag["responses"])] + + if panels: + # Named to distinguish it from the convolved summary + # below: this one shows the bare response functions, + # that one shows them after convolution with the pulse. + title = "Raw response functions from all mechanisms" + fig = self._stacked_figure(len(panels)) + for row, (component, key, name, axis_label) in enumerate(panels, start=1): + ax = fig.add_subplot(len(panels), 1, row) + for resp in diag["responses"]: + if not resp[key]: + continue + # Numbered with the 1-based mechanism slot, the + # same numbering the parameter log uses. + ax.plot(T1, component(resp["R"]), + label=f"{resp['number']}. {resp['mech_name']}") + ax.set_xlim(T_plot_min, T_plot_max) + ax.set_xlabel(self.DIAG_LABEL_T) + ax.set_ylabel(axis_label) + ax.set_title(name) + ax.legend(loc="best") + self._finish_stacked_figure(fig, title, len(panels)) + figures.append((title, fig)) + + combined = diag.get("combined") + if combined is not None: + # The same responses after convolution with the pulse, + # per mechanism plus their total. Laid out like the raw + # figure above: the name goes in the figure title and + # each panel names the quantity it shows. + title = "Convolved response from all mechanisms" + fig = self._stacked_figure(2) + curves, labels = combined["curves"], combined["labels"] + for ax, part, ylabel, panel in ( + (fig.add_subplot(211), np.real, self.DIAG_LABEL_DN, + "Index change"), + (fig.add_subplot(212), np.imag, self.DIAG_LABEL_DA, + "Absorption change")): + for label, curve in zip(labels, curves): + ax.plot(T1, part(curve), label=label) + ax.plot(T1, part(combined["total"]), label="Total") + ax.set_xlim(T_plot_min, T_plot_max) + ax.set_xlabel(self.DIAG_LABEL_T) + ax.set_ylabel(ylabel) + ax.set_title(panel) + ax.legend(loc="best") + self._finish_stacked_figure(fig, title, 2) + figures.append((title, fig)) + + esa = diag.get("esa") + if esa: + figures.extend(self._build_esa_figures(esa)) + + return figures + + @staticmethod + def _pop_mathtext(name: str) -> str: + """Turns a population name into mathtext: N_S_0 -> N_{S_0}, so + the state renders with its electronic term as a nested + subscript instead of showing the raw underscores.""" + parts = name.split("_") + if len(parts) == 3: + return f"{parts[0]}_{{{parts[1]}_{parts[2]}}}" + return name.replace("_", r"\_") + + def _build_esa_figures(self, esa): + """The seven BD_3_level_triplet diagnostic figures.""" + from matplotlib.figure import Figure + + figures = [] + # Same "N. " prefix as the response figures, so every diagnostic + # names the mechanism slot it came from. + prefix = f"{esa['number']}. " if esa.get("number") else "" + Y_interp, N0 = esa["Y_interp"], esa["N0"] + z, L = esa["z"], esa["L"] + tau_d, tau_e = esa["tau_d"], esa["tau_e"] + rad_fac = esa["rad_fac"] + + # Surfaces are drawn at the full-irradiance radial slice and + # drop the final depth step, exactly as the original's + # Y_interp(:,1:end-1,n,1) indexing did (that last z point is + # never written by the propagation loop). + TAU, Z = np.meshgrid(tau_d / tau_e, z[:-1] / L, indexing="ij") + for n, pop in enumerate(esa["pop_names"]): + fig = Figure(figsize=self.DIAG_FIGSIZE) + ax = fig.add_subplot(111, projection="3d") + ax.plot_surface(TAU, Z, Y_interp[:, :-1, n, 0] / N0, + cmap="viridis", linewidth=0, antialiased=True) + pop_math = self._pop_mathtext(pop) + ax.set_xlabel(r"$T$ ($\tau_e$)") + ax.set_ylabel(r"$Z$ ($L$)") + ax.set_zlabel(f"${pop_math}/N_t$") + ax.set_title(f"{prefix}Population of ${pop_math}$ vs. time") + fig.tight_layout() + figures.append((f"{prefix}Population of {pop}", fig)) + + # The excitation and probe transmission plots differ only in + # their x axis and the array plotted against it. The last + # radial factor is exactly 0, making the excitation ratio a + # 0/0: MATLAB produced a silent NaN and drew nothing for that + # trace, which errstate reproduces without a warning. + with np.errstate(invalid="ignore", divide="ignore"): + excitation_T = esa["I_0_e_arr"] / esa["I_0_e_norm"] + + for x_vals, y_vals, xlabel, title in ( + (z / L, excitation_T, r"$Z$ ($L$)", + "Transmission of excitation vs. position"), + (tau_d / tau_e, esa["I_p_end"], r"$T_d$ ($\tau_e$)", + "Transmission of probe vs. delay")): + fig = Figure(figsize=self.DIAG_FIGSIZE) + ax = fig.add_subplot(111) + # One trace per radial irradiance factor, labelled with + # that factor to 2 significant figures as the original's + # legend was. + for k, fac in enumerate(rad_fac): + ax.plot(x_vals, y_vals[:, k], label=f"{fac:.2g}") + ax.set_xlim(np.min(x_vals), np.max(x_vals)) + ax.set_xlabel(xlabel) + ax.set_ylabel(r"$T$ (unitless)") + ax.set_title(prefix + title) + ax.legend(loc="lower left", title=r"$I_e[r]/I_{e0}$", frameon=False) + fig.tight_layout() + figures.append((prefix + title, fig)) + + return figures + + def _refresh_diagnostics(self): + for child in self.diag_holder.winfo_children(): + child.destroy() + self._diag_canvases = [] + + diag = self.fit.get("diagnostics") if self.fit else None + if diag is None: + message = ("Diagnostics are off. Tick \"Show diagnostic plots " + "during Fit\" in the parameter panel and run Fit " + "again to populate this tab.") + ttk.Label(self.diag_holder, text=message, wraplength=600, + padding=20, foreground="#444").pack(anchor="w") + return + + if diag.get("note"): + ttk.Label(self.diag_holder, text=diag["note"], wraplength=600, + padding=(20, 12), foreground="#444").pack(anchor="w") + + for title, fig in self._build_diagnostic_figures(diag): + frame = ttk.LabelFrame(self.diag_holder, text=title, padding=4) + frame.pack(fill="x", padx=8, pady=6) + canvas = FigureCanvasTkAgg(fig, master=frame) + canvas.draw() + canvas.get_tk_widget().pack() + # Held so the canvases are not garbage collected. + self._diag_canvases.append(canvas) + + # ------------------------------------------------------------------ + # Export + # ------------------------------------------------------------------ + + def _on_export(self): + if self.data is None or self.fit is None: + return + default_name = self.params.filename.replace(".txt", "_fit.txt") + path = filedialog.asksaveasfilename( + title="Select filename for fit export", + initialdir=self.params.pathname or os.getcwd(), + initialfile=default_name, + defaultextension=".txt", + filetypes=[("Text files", "*.txt"), ("All files", "*.*")], + ) + if not path: + print("bd_fresnel_gui: fit export cancelled.") + return + + try: + T_interp = np.interp(self.data["tau_d_shifted"], self.fit["tau_d"], self.fit["T"]) + DeltaEoE_interp = np.interp(self.data["tau_d_shifted"], self.fit["tau_d"], self.fit["DeltaEoE"]) + Delta_n_interp = np.interp(self.data["tau_d_shifted"], self.fit["tau_d"], self.fit["Delta_n"]) + + export_data = np.column_stack([ + self.data["tau_d_shifted"], self.data["DeltaEoE"], self.data["T"], self.data["Delta_n"], + DeltaEoE_interp, T_interp, Delta_n_interp, + ]) + header = ("Delay (fs), DeltaE / E (Data), T (Data), Delta_n (data), " + "DeltaE / E (Fit), T (Fit), Delta_n (fit)") + np.savetxt(path, export_data, delimiter=",", fmt="%.8g", + header=header, comments="", newline="\r\n") + + # Images before the log: the log lists every file the + # export produced, so it has to be written last, once the + # image filenames are known. + image_paths = self._export_plot_images(path) + self._write_export_log(path, image_paths) + print(f"bd_fresnel_gui: export of {path} complete.") + self._save_settings() + except Exception: + messagebox.showerror("Export failed", traceback.format_exc().strip().splitlines()[-1]) + + def _export_plot_images(self, export_path): + """Saves the combined Transmission (left) / Deflection (right, + y-axis on the right) figure as .jpg and .svg alongside the + exported data/log files, plus every diagnostic figure as .jpg + when the fit was run with diagnostics enabled. Returns the + paths written, in the order written.""" + if self.data is None: + return [] + + # Built fresh here rather than reusing the on-screen figure: + # the displayed one is a different size and gets resized again + # by ResizableFigureCanvas as the window changes, so its layout + # is both wrong for print and potentially stale. + width = self.EXPORT_WIDTH_IN + height = width * self.SCREEN_FIGSIZE[1] / self.SCREEN_FIGSIZE[0] + fig = self._build_combined_figure(figsize=(width, height), print_style=True) + written = [] + for suffix, fmt, dpi in (("_combined.jpg", "jpg", self.EXPORT_DPI), + ("_combined.svg", "svg", None)): + path = self._sibling_path(export_path, suffix) + fig.savefig(path, format=fmt, **({"dpi": dpi} if dpi else {})) + written.append(path) + + written.extend(self._export_diagnostic_images(export_path)) + return written + + # Short filename suffixes for the figures that would otherwise get + # unwieldy names from their (deliberately descriptive) titles. + # Anything not listed falls back to a slug of its title. + DIAG_FILE_SUFFIXES = { + "Raw response functions from all mechanisms": "_raw_response", + "Convolved response from all mechanisms": "_convolved_response", + } + + @staticmethod + def _sibling_path(export_path: str, suffix: str) -> str: + """Names a file alongside the exported data, e.g. + scan_fit.txt -> scan_fit_combined.jpg.""" + return export_path.replace(".txt", suffix) + + @staticmethod + def _filename_slug(title: str) -> str: + """Turns a figure title into a safe filename fragment.""" + slug = "".join(c if c.isalnum() else "_" for c in title.lower()) + return "_".join(part for part in slug.split("_") if part) + + def _export_diagnostic_images(self, export_path): + """Writes each diagnostic figure as a .jpg next to the exported + data. Silently does nothing when the fit carries no diagnostics + (the checkbox was off), since they are an optional extra rather + than part of the standard export set. + + Figures are saved at the size they were built for the tab + rather than being rescaled to the fit image's 6.5 in width: + their text is sized in points, so resizing them would need the + same rescaling the on-screen figure does, and at 300 dpi a + 7 in figure is already 2100 px across. + """ + diag = self.fit.get("diagnostics") if self.fit else None + if not diag: + return [] + + written = [] + used = set() + for title, fig in self._build_diagnostic_figures(diag): + suffix = self.DIAG_FILE_SUFFIXES.get( + title, f"_diag_{self._filename_slug(title)}") + # Nothing currently produces two figures with the same + # title, but a duplicate would silently overwrite the + # earlier file, so disambiguate rather than lose one. + base, n = suffix, 2 + while suffix in used: + suffix, n = f"{base}_{n}", n + 1 + used.add(suffix) + + path = self._sibling_path(export_path, f"{suffix}.jpg") + fig.savefig(path, format="jpg", dpi=self.EXPORT_DPI) + written.append(path) + + if written: + print(f"bd_fresnel_gui: wrote {len(written)} diagnostic image(s) " + f"at {self.EXPORT_DPI} dpi.") + return written + + def _build_log_text(self, exported_files=None): + """ + Builds the full log report as a string. Used both to write the + _log.txt file on Export and to populate the Log tab immediately + after a Fit completes (nothing has been written at that point, + so leave exported_files unset and the file manifest is + omitted). + + Section order matches the GUI's left-panel field order top to + bottom: Data Columns -> Simulation grid (not itself a GUI + field, kept as a preamble) -> Pump (Excitation) Beam -> Probe + Beam -> Material @ Pump Wavelength -> Material @ Probe + Wavelength -> System Geometry -> Mechanisms -> Calculated + Parameters (probe) -> Calculated Parameters (pump) -> Other + (rho). The column numbers are 1-based, as entered in the GUI. + """ + from bd_fresnel_core import MECHANISM_PARAM_SPECS + + p = self.params + lines = [] + lines.append(f"{datetime.datetime.now()}: Begin beam deflection program (bd_fresnel_gui.py).\n") + lines.append(f"Import data file {p.import_filepath}.\n") + + lines.append("Data Columns:") + lines.append(f" tau_d column: {p.col_tau_d}") + lines.append(f" T column: {p.col_T}") + lines.append(f" DeltaEoE column: {p.col_DeltaEoE}") + lines.append(f" Delimiter: {describe_delimiter(p.delimiter)}\n") + + # The delay grid is included so a run is reproducible from the + # log alone: T_d_min/T_d_max are not entered but derived from + # the imported scan's delay range at fit time. + lines.append("Simulation Parameters:") + lines.append(f" X_num: {p.X_num}") + lines.append(f" X_max: {p.X_max} w_0") + lines.append(f" T_num: {p.T_num}") + lines.append(f" T_min: {p.T_min} tau_p") + lines.append(f" T_max: {p.T_max} tau_p") + lines.append(f" T_d_num: {p.T_d_num}") + lines.append(f" T_d_min: {p.T_d_min:.6g} tau_p") + lines.append(f" T_d_max: {p.T_d_max:.6g} tau_p\n") + + lines.append("Pump (Excitation) Beam:") + lines.append(f" E_p: {p.E_p} uJ") + lines.append(f" tau_p_FWHM: {p.tau_p_FWHM} fs") + lines.append(f" tau_p (HW1/eM): {p.tau_p:6.3f} fs") + lines.append(f" w_0p: {p.w_0p} um") + lines.append(f" lambda_p: {p.lambda_p} nm\n") + + lines.append("Probe Beam:") + lines.append(f" tau_FWHM: {p.tau_FWHM} fs") + lines.append(f" tau (HW1/eM): {p.tau:6.3f} fs") + lines.append(f" w_0: {p.w_0} um") + lines.append(f" lambda: {p.lambda_} nm\n") + + lines.append("Material @ Pump Wavelength:") + lines.append(f" R_p: {p.R_p * 100:6.3f} %") + lines.append(f" alpha_p: {p.alpha_p:6.3f} cm^-1") + lines.append(f" n_p: {p.n_p}") + lines.append(f" dndl_p: {p.dndl_p:6.6f} um^-1") + lines.append(f" alpha_2d: {p.alpha_2d} e-11 m/W\n") + + lines.append("Material @ Probe Wavelength:") + lines.append(f" R: {p.R * 100:6.3f} %") + lines.append(f" alpha: {p.alpha:6.3f} cm^-1") + lines.append(f" n: {p.n}") + lines.append(f" dndl: {p.dndl:6.6f} um^-1\n") + + lines.append("System Geometry:") + lines.append(f" l: {p.l} mm") + lines.append(f" d: {p.d} cm") + lines.append(f" shift: {p.shift} fs") + lines.append(f" x_0: {p.x_0} w_0_p\n") + + for i, mech in enumerate(p.mech): + if mech.name == "None (both)": + continue + lines.append(f"Mechanism {i + 1}:") + lines.append(f" Type: {mech.name}") + specs = MECHANISM_PARAM_SPECS.get(mech.name, []) + for j, (pname, punits) in enumerate(specs): + spacing = " " * max(1, 20 - len(pname)) + lines.append(f" {pname}:{spacing}{mech.param[j]} {punits}") + lines.append("") + + lines.append("Calculated Parameters (probe):") + lines.append(f" n_g: {p.ng:6.3f}") + lines.append(f" T_lin: {p.Tlin * 100:6.3f} %") + lines.append(f" z_0: {p.z_0 * 1e3:6.3f} mm\n") + + lines.append("Calculated Parameters (pump):") + lines.append(f" n_g: {p.ng_p:6.3f}") + lines.append(f" T_lin: {p.Tlin_p * 100:6.3f} %") + lines.append(f" z_0: {p.z_0_p * 1e3:6.3f} mm") + lines.append(f" I_0: {p.I_0_p * 1e-13:6.3f} GW/cm^2\n") + + lines.append("Other:") + lines.append(f" rho: {p.rho:6.3f}\n") + + if exported_files: + # Every file this export run produced. They all land in one + # directory, so that is named once in the header and the + # entries are bare filenames. The count varies: the two + # combined plots are always written, and one .jpg per + # diagnostic figure is added when the fit was run with + # diagnostics enabled. + directory = os.path.dirname(exported_files[0]) or "." + lines.append(f"Exported {len(exported_files)} file(s) to {directory}:") + for path in exported_files: + lines.append(f" {os.path.basename(path)}") + lines.append("") + lines.append("Please cite the following references when using products from this program.\n") + lines.append(' 1: Reichert, M., et al. (2014). "Temporal, spectral, and polarization ' + 'dependence of the nonlinear optical response of carbon disulfide." Optica 1(6): 436.\n') + lines.append(' 2: Reichert, M., et al. (2014). "Temporal, spectral, and polarization ' + 'dependence of the nonlinear optical response of carbon disulfide: supplementary ' + 'material." Optica 1(6): 436.\n') + lines.append(' 3: Ferdinandus, M. R., et al. (2013). "Beam deflection measurement of time ' + 'and polarization resolved ultrafast nonlinear refraction." Opt Lett 38(18): 3518-3521.\n') + + return "\n".join(lines) + + def _write_export_log(self, export_path, image_paths=()): + log_path = self._sibling_path(export_path, "_log.txt") + # The manifest covers the data file, the images, and this log + # itself -- everything the export run produced. + exported = [export_path, *image_paths, log_path] + text = self._build_log_text(exported_files=exported) + with open(log_path, "w+", newline="\r\n") as f: + f.write(text) + + # ------------------------------------------------------------------ + # Exit + # ------------------------------------------------------------------ + + def _on_exit(self): + self._save_settings() + print("bd_fresnel_gui: end BD_Fresnel_GUI.") + self.destroy() + + +if __name__ == "__main__": + app = BDFresnelApp() + app.protocol("WM_DELETE_WINDOW", app._on_exit) + app.mainloop() diff --git a/set_params_dialog.py b/set_params_dialog.py new file mode 100644 index 0000000..de2bac8 --- /dev/null +++ b/set_params_dialog.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +set_params_dialog.py +===================== + +Tkinter port of set_params_GUI.m / set_params_GUI.fig -- a small modal +dialog for entering the numeric parameters of whichever mechanism is +currently selected in one of the seven mechanism slots of the main +BD_Fresnel_GUI window. + +Behavior matched against the original: + * The dialog's title and header both read " + parameters", exactly as MATLAB's `st_mechanism_parameters` label. + * Only as many parameter rows are shown as that mechanism actually + uses (0 for "None (both)" up to 10 for the ESA/triplet mechanism); + the rest are hidden entirely, matching the original's + show/hide-unused-input-boxes logic. + * If you re-open the dialog for the SAME mechanism it was last set + to, the previously entered values are restored. If you've changed + mechanisms, all fields reset to 0 -- matching set_params_GUI's + "restore previous settings if required" check. + * Each field is validated as a real number on edit; an invalid + entry is rejected (reverted to its last valid value) with a + message printed to the console, mirroring the original's + str2double() validation and disp() logging. + +One intentional behavior change from the original: MATLAB's dialog had +no Cancel button and no handled window-close action (only the OK +button called uiresume), so closing it via the window's [X] button +would leave the caller's uiwait() blocked forever. Here, closing the +window via [X] is treated the same as pressing OK (whatever is +currently entered is accepted) rather than hanging the application -- +a deliberate usability improvement, not a fidelity gap in the physics. + +Usage: + from set_params_dialog import open_set_params_dialog + new_mechanism = open_set_params_dialog(parent, "Collisional (NLR)", + previous_mechanism=old_mech) +""" + +import tkinter as tk +from tkinter import ttk + +from bd_fresnel_core import Mechanism, MECHANISM_PARAM_SPECS + + +class SetParamsDialog(tk.Toplevel): + def __init__(self, parent, mechanism_name: str, previous_mechanism: Mechanism = None): + super().__init__(parent) + self.mechanism_name = mechanism_name + self.result: Mechanism = None + + self.title(f"{mechanism_name} parameters") + self.resizable(False, False) + + specs = MECHANISM_PARAM_SPECS.get(mechanism_name, []) + + # Restore previous values only if this is the same mechanism + # as before; otherwise every field starts at 0 -- matches + # set_params_GUI_OpeningFcn's restore-if-same-mechanism check. + if previous_mechanism is not None and previous_mechanism.name == mechanism_name: + prev_values = list(previous_mechanism.param) + else: + prev_values = [] + prev_values = (prev_values + [0.0] * 10)[:10] + + header = ttk.Label(self, text=f"{mechanism_name} parameters", + font=("TkDefaultFont", 10, "bold")) + header.grid(row=0, column=0, columnspan=2, padx=10, pady=(10, 6), sticky="w") + + self._vars = [] + self._entries = [] + self._last_valid = list(prev_values) + + row = 1 + for i in range(10): + if i < len(specs): + name, units = specs[i] + ttk.Label(self, text=f"{name} ({units})", width=22, anchor="w").grid( + row=row, column=0, padx=(10, 4), pady=3, sticky="w" + ) + var = tk.StringVar(value=self._format(prev_values[i])) + entry = ttk.Entry(self, textvariable=var, width=14, justify="right") + entry.grid(row=row, column=1, padx=(0, 10), pady=3, sticky="e") + entry.bind("", lambda e, idx=i: self._validate(idx)) + entry.bind("", lambda e, idx=i: self._validate(idx)) + self._vars.append(var) + self._entries.append(entry) + row += 1 + else: + self._vars.append(None) + self._entries.append(None) + + button_row = ttk.Frame(self) + button_row.grid(row=row, column=0, columnspan=2, pady=(8, 10)) + ttk.Button(button_row, text="OK", command=self._on_ok, width=10).pack() + + self.protocol("WM_DELETE_WINDOW", self._on_ok) + self.transient(parent) + self.grab_set() + if self._entries and self._entries[0] is not None: + self.after(10, self._entries[0].focus_set) + + @staticmethod + def _format(value: float) -> str: + # MATLAB's num2str-equivalent-enough default formatting. + if value == int(value): + return str(int(value)) + return repr(float(value)) + + def _validate(self, idx): + var = self._vars[idx] + if var is None: + return + try: + value = float(var.get()) + except ValueError: + name = MECHANISM_PARAM_SPECS[self.mechanism_name][idx][0] + print(f"set_params_dialog: '{name}' must be a real number; reverting.") + value = self._last_valid[idx] + self._last_valid[idx] = value + var.set(self._format(value)) + + def _on_ok(self): + values = [0.0] * 10 + for i, var in enumerate(self._vars): + if var is None: + continue + try: + values[i] = float(var.get()) + except ValueError: + values[i] = self._last_valid[i] + self.result = Mechanism(name=self.mechanism_name, param=values) + self.grab_release() + self.destroy() + + +def open_set_params_dialog(parent, mechanism_name: str, + previous_mechanism: Mechanism = None) -> Mechanism: + """Opens the dialog modally (blocks the caller until it's closed) + and returns the resulting Mechanism.""" + dialog = SetParamsDialog(parent, mechanism_name, previous_mechanism) + parent.wait_window(dialog) + return dialog.result + + +if __name__ == "__main__": + # Small standalone demo/harness. + root = tk.Tk() + root.title("set_params_dialog demo") + + result_var = tk.StringVar(value="(no result yet)") + ttk.Label(root, textvariable=result_var, padding=20).pack() + + last_mech = [Mechanism(name="Collisional (NLR)", param=[5, 100, 500] + [0] * 7)] + + def launch(): + mech = open_set_params_dialog(root, "Collisional (NLR)", last_mech[0]) + last_mech[0] = mech + result_var.set(f"name={mech.name!r} param={mech.param}") + + ttk.Button(root, text="Open Collisional (NLR) params...", command=launch).pack(pady=10) + root.mainloop()