#!/usr/bin/env python3 # -*- coding: utf-8 -*- # BD Fresnel - physics and parameter model # # Copyright (C) 2019-2026 Manuel R. Ferdinandus # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ 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). """ __version__ = "3.0" import copy 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, erfcx from dataclasses import dataclass, field from typing import List # 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 _gauss_erfcx(p, y): """exp(-p^2) * erfcx(y), where erfcx(y) = exp(y^2) erfc(y). The product exp(-p^2) erfc(y) exp(y^2) is finite and well scaled for the (p, y) pairs the electronic response produces, even where each factor alone overflows. Used to evaluate that response without forming exp(large) and erf-differences that cancel to zero. erfcx itself overflows for strongly negative y, so that side uses erfcx(y) = 2 exp(y^2) - erfcx(-y). The reflected exponent y^2 - p^2 is non-positive wherever this is called with y < 0, so neither branch can overflow.""" p, y = np.broadcast_arrays(np.asarray(p, dtype=float), np.asarray(y, dtype=float)) out = np.empty(y.shape, dtype=float) pos = y >= 0 out[pos] = np.exp(-p[pos] ** 2) * erfcx(y[pos]) neg = ~pos if np.any(neg): out[neg] = (2 * np.exp(y[neg] ** 2 - p[neg] ** 2) - np.exp(-p[neg] ** 2) * erfcx(-y[neg])) return out 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)", ] # The empty slot. Its "(both)" suffix is inherited from the original # app's list and carries no meaning -- it contributes nothing -- so it # stays selectable in every mode. NO_MECHANISM = "None (both)" # Measurement modes. Beam deflection is the program's original # behaviour. Pump probe centres the probe on the pump (x_0 = 0), where # the deflection signal vanishes by symmetry, and so fits transmission # alone. Only mechanisms with an absorptive part can change the # transmission, so the purely refractive ones are excluded. MODE_BEAM_DEFLECTION = "beam_deflection" MODE_PUMP_PROBE = "pump_probe" MODES = (MODE_BEAM_DEFLECTION, MODE_PUMP_PROBE) # Run modes, independent of the measurement mode above. Fitting is the # program's original behaviour: a measured scan is imported and the # calculation compared against it. Simulation imports nothing and # computes the signal from the parameters alone, over a delay range # entered by hand rather than taken from a file. RUN_MODE_FITTING = "fitting" RUN_MODE_SIMULATION = "simulation" RUN_MODES = (RUN_MODE_FITTING, RUN_MODE_SIMULATION) # Algorithms, independent of the two modes above. Fresnel propagation is # the original method: build the field at the exit face, propagate it to # the detector by FFT, and integrate the irradiance over each half of # the detector. Semi-analytical uses closed-form expressions for the # power difference and total at the detector, already integrated over # the detector plane, leaving only an integral over time at each delay. ALGO_FRESNEL = "fresnel" ALGO_SEMI_ANALYTICAL = "semi_analytical" ALGORITHMS = (ALGO_FRESNEL, ALGO_SEMI_ANALYTICAL) # Half-width of the time window the semi-analytical integral runs over, # in multiples of T = tau / tau_e, centred on each delay. SA_WINDOW_HALF_WIDTHS = 5.0 # PROVISIONAL, NOT DERIVED. Coefficient on the absorptive term in dP's # bracket. The term as derived reproduces neither the sign nor the # magnitude the Fresnel propagation gives: with a purely absorptive # mechanism the two disagree by a factor of about -69, correlation # exactly -1. Dividing by D = d/(pi w_0^2/lambda) = d/z_0 accounts for # the distance and wavelength dependence exactly (constant to 0.1% over # 30x in d and 2.6x in lambda) and, because the Rayleigh range carries # the pi, for the pi as well: with the earlier D = d/(w_0^2/lambda) the # leftover factor was -2.869, and it is now -0.9133, smaller by # 3.141593 to seven digits. It is also exactly independent of sample # thickness at constant alpha_2*l. # # -1/(1 + 2W^2) was MEASURED against the Fresnel path, not derived: # residual*(1 + 2W^2) is flat at -0.968 .. -0.923 over an 8.8x range in # w_0 and extrapolates to -0.97 ~ -1 as W -> 0. It closes the two # methods to within about 5%, worsening with W. The (1 + 2W^2) # grouping is the one that already appears in R, which suggests a # common origin in the overlap integral. # # Replace this with the derived coefficient when it is available; it # is isolated here so that swapping it touches nothing else. def SA_ABSORPTIVE_FACTOR(W): return -1.0 / (1 + 2 * W ** 2) # Step for both the response axis and the time integral, in tau_e. Sized # by resolution rather than by T_num: T_num sets the probe window for # the Fresnel grid, whereas the response axis here spans the whole delay # range and the material response varies on the pulse timescale, so # reusing T_num would undersample it badly. Both axes are 1-D, so a fine # step is cheap. SA_TIME_STEP = 0.02 def mechanism_allowed(name: str, mode: str) -> bool: """Whether a mechanism may occupy a slot in the given mode. Pump probe admits the absorptive (NLA) and mixed (both) mechanisms, plus the empty slot, and excludes the purely refractive (NLR) ones. A mixed mechanism contributes its absorptive part to the transmission; its refractive part produces no deflection with the probe centred.""" if mode == MODE_PUMP_PROBE: return name == NO_MECHANISM or name.endswith(("(NLA)", "(both)")) return name in MECHANISM_NAMES def mechanism_names_for_mode(mode: str) -> List[str]: """The mechanism pull-down's choices in the given mode, in the original list order.""" return [n for n in MECHANISM_NAMES if mechanism_allowed(n, mode)] # 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_2el", "e-11 m/W"), ("n_2el", "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_e: float = 1.36 # pump pulse energy [uJ] tau_e_FWHM: float = 55.0 # pump pulse width, FWHM of I [fs] w_0_e: float = 246.0 # pump spot size, HW1/e^2 of I [um] lambda_e: float = 800.0 # pump wavelength [nm] # --- probe beam: raw GUI-entered values --- tau_p_FWHM: float = 60.0 # probe pulse width, FWHM of I [fs] w_0_p: float = 43.0 # probe spot size, HW1/e^2 of I [um] lambda_p: float = 650.0 # probe wavelength [nm] # --- material parameters at pump wavelength --- R_e: float = 0.0 # reflectivity of pump alpha_e: float = 0.0 # pump linear absorption coefficient [cm^-1] n_e: float = 1.4533 # refractive index at pump wavelength dndl_e: float = -0.017284 # dispersion dn/dlambda at pump [um^-1] alpha_2d_e: float = 0.0 # pump degenerate 2PA coefficient [1e-11 m/W] # --- material parameters at probe wavelength --- R_p: float = 0.0 # reflectivity of probe alpha_p: float = 0.0 # probe linear absorption coefficient [cm^-1] n_p: float = 1.4565 # refractive index at probe wavelength dndl_p: 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_0_e] # --- derived / calculated values (set by calc_beam_params) --- tau_e: float = 0.0 # pump pulse width, HW1/e of I [fs] (derived from tau_e_FWHM) tau_p: float = 0.0 # probe pulse width, HW1/e of I [fs] (derived from tau_FWHM) sigma_e: float = 0.0 # pump linear-absorption parameter (unitless) I_0_e: float = 1.0 # peak pump irradiance [W/m^2] ng_e: float = 1.0 # group index at pump ng_p: float = 1.0 # group index at probe rho: float = 0.0 # GVM parameter z_0_p: float = 0.0 # probe Rayleigh range [m] (display only) z_0_e: float = 0.0 # pump Rayleigh range [m] (display only) Tlin_p: float = 1.0 # linear transmission of probe (display only) Tlin_e: 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 # --- measurement mode (see set_mode) --- mode: str = MODE_BEAM_DEFLECTION # --- run mode: fit an imported scan, or simulate without one --- run_mode: str = RUN_MODE_FITTING # --- algorithm: Fresnel propagation or the semi-analytical form --- algorithm: str = ALGO_FRESNEL # Beam-deflection settings put aside while in pump-probe mode, and # restored on switching back: the x_0 that pump probe forces to 0, # and the mechanism slots as they were before the non-absorptive # ones were cleared. Unused (and the list empty) in beam deflection. x_0_beam_deflection: float = 0.5 mech_beam_deflection: List[Mechanism] = field(default_factory=list) # --- 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_e, 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_e t_exp_f = tau_exp_f / tau_e 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_e, 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_e omega_stdn = omega_std * tau_e tau_lfn = tau_lf / tau_e 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_e, T1): T1 = np.asarray(T1, dtype=float) if n_2v != 0 and w_0v > 0 and tau_vf > 0: w_0vn = w_0v * tau_e tau_vfn = tau_vf / tau_e 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): """ NAMING: `_e` is the excitation (pump) beam and `_p` the probe, as in BD_3_level_triplet.m, I_e_func.m and excite_prop.m, from which this was transliterated -- and, since the beam subscripts were reassigned, as everywhere else in this module too. `n_g_p`, `v_p` and `I_p` here are probe quantities, and no translation is needed to read this against the MATLAB. 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, response_only: bool = False): """ 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_e = params.lambda_e * 1e-9 tau_e = params.tau_e * 1e-15 w_0_e = params.w_0_e * 1e-6 lambda_p = params.lambda_p * 1e-9 tau_p = params.tau_p * 1e-15 w_0_p = params.w_0_p * 1e-6 d = params.d * 1e-2 X0 = params.x_0 L = params.l * 1e-3 alpha_p = params.alpha_p * 100 alpha_2d_e = params.alpha_2d_e * 1e-11 sigma_e = params.sigma_e I_0_e = params.I_0_e ng_e = params.ng_e ng_p = params.ng_p 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_p * L / 2 t = tau_p / tau_e W_0_e = w_0_e / w_0_p D = d / w_0_p LAMBDA = lambda_p / w_0_p 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_e_0 = np.exp(-((X + X0 * W_0_e) ** 2 + Y ** 2) / W_0_e ** 2) sigma_e2 = I_0_e * a_e_0 * alpha_2d_e * 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_2el = alpha_2el = 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_2el = p[0] * 1e-11 n_2el = p[1] * 1e-19 if rho < rho_min and sigma_e == 0: I_RESP = I_0_e * (2 * n_2el + 1j * alpha_2el) * np.exp(-(T + T_d) ** 2) * (-1 + sigma_e2) elif rho < rho_min and sigma_e != 0: A1 = np.exp(-2 * sigma_e - (T + T_d) ** 2) A2 = sigma_e - sigma_e2 + sigma_e / np.tanh(sigma_e) A3 = np.sinh(sigma_e) ** 2 I_RESP = I_0_e * (2 * n_2el + 1j * alpha_2el) * (A1 * A2 * A3) / (2 * sigma_e ** 2) elif rho != 0 and sigma_e == 0: A1 = 2 * np.exp(-rho ** 2 - (T + T_d) ** 2) A2 = sigma_e2 * (np.exp(rho ** 2) - np.exp(2 * rho * (T + T_d))) A3 = rho * (-1 + 2 * sigma_e2) - 2 * sigma_e2 * (T + T_d) A4 = erf(rho - (T + T_d)) + erf(T + T_d) I_RESP = I_0_e * (2 * n_2el + 1j * alpha_2el) * ((A1 * A2) - (A3 * A4) * np.sqrt(np.pi)) / (2 * rho ** 2) elif rho != 0 and sigma_e != 0: # Algebraically identical to the form in # BD_Fresnel_func_ni.m, rearranged so that nothing # overflows. That form was # A1 = exp(sig(sig + 2 rho(-rho + u))/rho^2)(sig-sig2) # A2 = erf(rho - sig/rho - u) + erf(sig/rho + u) # and the two analogous terms in 2 sig/rho, with # u = T + T_d. Writing k = sig/rho and a = k + u, A2 is # erfc(a - rho) - erfc(a), and A1's prefactor # exp(-k^2 - 2 sig) combines with exp(2 k a) so that # every surviving exponent is non-positive: # A1 A2 = (sig-sig2)[G(u-rho, k+u-rho) # - exp(-2 sig) G(u, k+u)] # A3 A4 = sig2 [G(u-rho, 2k+u-rho) # - exp(-4 sig) G(u, 2k+u)] # with G = _gauss_erfcx. As written originally, A1 grew # as exp(sig^2/rho^2 + 2 sig u/rho) while A2 fell to # zero, so their product was lost to cancellation long # before it overflowed: at rho = 0.4336 (l = 0.5 mm) the # result was already wrong over 8.6% of the delay axis # at sigma_e = 2.5 -- returning exactly 0.0, with no NaN # to signal it -- and became NaN above sigma_e = 3. This # form matches the original evaluated at 600 decimal # digits to 1e-16..1e-11 relative, everywhere the # original works and everywhere it does not. u_sum = T + T_d k = sigma_e / rho term_1 = (sigma_e - sigma_e2) * ( _gauss_erfcx(u_sum - rho, k + u_sum - rho) - np.exp(-2 * sigma_e) * _gauss_erfcx(u_sum, k + u_sum)) term_2 = sigma_e2 * ( _gauss_erfcx(u_sum - rho, 2 * k + u_sum - rho) - np.exp(-4 * sigma_e) * _gauss_erfcx(u_sum, 2 * k + u_sum)) I_RESP = (I_0_e * (2 * n_2el + 1j * alpha_2el) * (term_1 + term_2) * np.sqrt(np.pi) / (2 * rho * sigma_e)) 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_e, 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_e, 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_e, 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_e, 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_e, lambda_e, ng_e, tau_e, w_0_e, ng_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, T_d_vec * tau_e, X_vec * w_0_p, Y_vec * w_0_p, 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_e, 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_e, 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_e, 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_e_pulse = I_0_e * np.exp(-T1 ** 2) if np.allclose(I_e_pulse, 0): I_e_pulse = np.zeros_like(T1) I_e_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_e_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_e20 = I_0_e * alpha_2d_e * L / 2 zoom_pts = 2 ** 8 att_arr = np.linspace(0, 1, zoom_pts) # Normalised pump irradiance I_e(z)/I_e(0) at fractional depth # att_arr = z/L, which weights the response in the depth # integral below. Solving # dI_e/dz = -alpha_e I_e - alpha_2d_e I_e^2 # and substituting sigma_e = alpha_e L / 2 and # sigma_e20 = I_0_e alpha_2d_e L / 2 gives # exp(-2 sigma_e z/L) # / [1 + (sigma_e20/sigma_e)(1 - exp(-2 sigma_e z/L))]. # # This replaces the two-branch form carried over verbatim from # BD_Fresnel_func_ni.m. That form's sigma_e2 != 0 branch, # sqrt((B1 B2)/sigma_e), failed three ways: it did not reduce to # its own sigma_e2 == 0 branch as sigma_e20 -> 0 (it decayed as # exp(-sigma_e z/L), half the correct rate), it divided by zero # whenever alpha_e was zero, and it took the square root of a # negative number whenever sigma_e20 > sigma_e -- so every run # combining pump two-photon absorption with a non-instantaneous # mechanism returned NaN at every delay. Dropping that stray # square root recovers B1*B2/sigma_e, which is exactly the # expression above linearised in sigma_e20, confirming the # intent; the exact form is used here instead, since it costs # nothing and is positive and monotone for any alpha_2d_e >= 0. # # (1 - exp(-2 sigma_e z/L))/sigma_e is formed with expm1 and # takes its sigma_e -> 0 limit, 2 z/L, so pure two-photon pump # absorption (alpha_e = 0, alpha_2d_e != 0) gives the finite # 1/(1 + 2 sigma_e20 z/L) rather than dividing by zero. decay = np.exp(-2 * sigma_e * att_arr) if sigma_e > 0: buildup = -np.expm1(-2 * sigma_e * att_arr) / sigma_e else: buildup = 2 * att_arr # The denominator is >= 1 for any alpha_2d_e >= 0, which is the # physical range: a passive material's degenerate 2PA # coefficient is non-negative. A negative alpha_2d_e means # two-photon gain on the pump, and the solution above then # diverges at a finite depth -- the pump grows without bound # before reaching the exit face and the depth average does not # exist. That is refused outright rather than returned as a huge # number, in the same spirit as the pump-2PA mpmath check. atten_denom = 1 + sigma_e20 * buildup if np.any(atten_denom <= 0): # buildup is monotone increasing in depth, so the pole is # first reached where it is largest. |sigma_e20| * buildup # = 1 there, and sigma_e20 is linear in alpha_2d_e. limit = abs(params.alpha_2d_e) / (abs(sigma_e20) * float(np.max(buildup))) raise ValueError( "alpha_2d_e is negative enough that the pump diverges " "inside the sample (two-photon gain), so the pump " "irradiance has no finite depth average. Use " f"alpha_2d_e >= 0, or keep |alpha_2d_e| below {limit:.4g} " "e-11 m/W for this thickness and pump irradiance." ) atten_fac = decay / atten_denom # 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: # Substituting T1 = (T + T_d) - rho + rho*zeta turns the # branch above into int_0^1 Resp_tot(...) atten_fac dzeta, a # depth average, so its rho -> 0 limit is the response at a # single instant times the MEAN of atten_fac -- not the bare # response, which is what BD_Fresnel_func_ni.m used here. # Dropping that mean left the non-instantaneous response # unattenuated by the pump for any sample with no walk-off: # at alpha_e = 10 cm^-1 and l = 0.5 mm it was 1.27x too # large, and the discontinuity grew with alpha_e. With no # pump absorption atten_fac is 1 and the mean is exactly 1, # so this changes nothing for alpha_e = alpha_2d_e = 0. NI_RESP = Resp_tot_interp(low_base) * _trapz(atten_fac, att_arr) # --- 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_p) * L * np.real(TOT_RESP) Gamma = L * np.imag(TOT_RESP) CHI_RESP = eta + 1j * Gamma if response_only: # The semi-analytical path needs only the material response as a # function of absolute time. TOT_RESP depends on T and T_d solely # through their sum (the walk-off integral runs from T+T_d-rho to # T+T_d, and the instantaneous branches go as exp(-(T+T_d)^2)), # and carries no x/y dependence unless the pump two-photon term # sigma_e2 is nonzero -- so one row of the grid is the whole # function. The caller supplies a single T_d = 0 so that the T # axis *is* the time axis. resp = np.asarray(TOT_RESP) if resp.ndim == 4: resp = resp[0, 0, :, :] resp = np.reshape(resp, (len(T_vec), len(T_d_vec))) return dict(T_vec=T_vec, T_d_vec=T_d_vec, TOT_RESP=resp, diagnostics=_build_diagnostics( params, T1, T1_max, R_n, is_resp, NI_resp_diag, diag_responses, esa_diag, have_electronic, n_2el, alpha_2el, I_0_e)) # --- propagation to detector --- spacePart = np.exp(-X ** 2 - Y ** 2) a_out = (spacePart * np.exp(-sigma - ((-rho + T) ** 2 / t ** 2) / 2 + 1j * (a_e_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_e * 1e15 DeltaEoE = (E_left - E_right) / E_tot Delta_n = DeltaEoE / ((2 * np.pi / lambda_p) * L * np.sqrt(2 / np.e) * (w_0_p / w_0_e) * (2 / np.sqrt(np.pi))) # Largest nonlinear phase and absorption exponent anywhere on the # grid. Reported so the small-signal regime is visible: the # semi-analytical algorithm's dP is first order in the response, # while this one propagates the full field, so the two part company # once eta_peak is no longer small: measured on the 4-layer # mechanisms, the peak of DeltaEoE sits at the same delay to within # 0.0003 tau_e at eta_peak = 0.14, but 0.0035 at 1.41, 0.077 at 5.6 # and 0.36 at 14.1. Neither sample thickness (0.05 to 2 mm), nor # walk-off (rho 0.04 to 1.7), nor pump absorption (sigma_e 0 to 10) # moves it once eta_peak is held fixed, so eta_peak alone is the # yardstick. Measured on the same (T, T_d) grid the signal was # computed on, so it costs one pass over an array already held. result = dict(T=T_out, tau_d=tau_d_out, DeltaEoE=DeltaEoE, Delta_n=Delta_n, eta_peak=float(np.max(np.abs(eta))), Gamma_peak=float(np.max(np.abs(Gamma))), diagnostics=_build_diagnostics( params, T1, T1_max, R_n, is_resp, NI_resp_diag, diag_responses, esa_diag, have_electronic, n_2el, alpha_2el, I_0_e)) if params.diagnostics: _diag_print("BD_Fresnel_func - calculation time: " f"{time.time() - _t_start:g} s.") return result def _response_vs_time(params: BDFresnelParams, u_min: float, u_max: float, n_pts: int): """Material response as a function of absolute time, on a grid spanning [u_min, u_max]. The time axis is carried on the *delay* coordinate, not the probe coordinate. The convolution grid the response is built on is sized as T1_max = T_d_max + 2*T_fac + |rho|, so asking for the response over a wide window through T alone would leave everything past |T1| ~ 10 to be linearly extrapolated -- silently, and with the wrong sign once the response has decayed. Putting the window on T_d sizes that grid to match. T is then a single point at 0, and a minimal spatial grid suffices since the response has no x/y dependence. Returns (u, TOT_RESP, diagnostics). """ q = copy.deepcopy(params) q.T_min = q.T_max = 0.0 q.T_num = 2 q.T_d_min, q.T_d_max, q.T_d_num = u_min, u_max, n_pts q.X_num, q.X_max = 2, 1.0 out = BD_Fresnel_func_ni(q, response_only=True) u = out["T_vec"][0] + out["T_d_vec"] return u, out["TOT_RESP"][0, :], out["diagnostics"] def BD_Fresnel_func_sa(params: BDFresnelParams): """Semi-analytical signal calculation. Instead of propagating the exit field to the detector, this uses closed-form expressions for the power difference and total at the detector, already integrated over the detector plane: dP = 2 exp[-2 X0^2 - (rho - tau + tau_d)^2 / T^2 - 2 exp(-2 X0^2) H_p(tau)] sqrt(2 pi) W^3 X0 (R H_dp(tau) + H_p(tau)) P = 1/2 exp[- (rho - tau + tau_d)^2 / T^2 - 2 exp(-2 X0^2) H_p(tau)] pi W^2 with tau = t / tau_e, T = tau / tau_e (probe over pump width), W = w_0 / w_0_e, X0 the pump-probe offset in units of w_0_e, rho the walk-off, R = exp(2 X0^2 - 2 X0^2/(1 + 2 W^2)) / (1 + 2 W^2)^2, and H_p / H_dp the absorptive and refractive parts of the material response -- the same Gamma and eta the Fresnel path forms from TOT_RESP, taken on axis. Integrating each over time at fixed delay gives the energy difference and total; their ratio is the deflection signal, and the total normalised to its value before the pump arrives is the transmission. """ _t_start = time.time() lambda_p = params.lambda_p * 1e-9 L = params.l * 1e-3 w_0_p = params.w_0_p * 1e-6 w_0_e = params.w_0_e * 1e-6 tau_p_fs = params.tau_e rho = params.rho X0 = params.x_0 T_ratio = params.tau_p / params.tau_e # T = tau / tau_e W = w_0_p / w_0_e # W = w_0 / w_0_e # R_geom: the geometric factor from the expressions. The name is # spelled out because the expressions call it R, which since the # probe rename is also the stem of params.R_p, the surface # reflectivity -- an unrelated quantity. R_geom = np.exp(2 * X0 ** 2 - 2 * X0 ** 2 / (1 + 2 * W ** 2)) / (1 + 2 * W ** 2) ** 2 atten_X0 = np.exp(-2 * X0 ** 2) # Propagation distance in units of the probe's Rayleigh range, # D = d / (pi w_0^2 / lambda) = d / z_0. The absorptive term in dP's # bracket is divided by it: an absorption gradient displaces the # beam centroid by a fixed amount at the sample, which then dilutes # as the beam expands over the distance to the detector. The # refractive term has no such factor -- a tilt and the beam's own # divergence both scale with d, so their ratio does not. D_prop = (params.d * 1e-2) / (np.pi * w_0_p ** 2 / lambda_p) T_d_vec = np.linspace(params.T_d_min, params.T_d_max, params.T_d_num + 1) half_window = SA_WINDOW_HALF_WIDTHS * T_ratio # The response is needed over every tau the integrals touch, plus # the reference delay used to normalise the transmission. ref_delay = min(-3.0 * rho, -3.0) lo = min(float(np.min(T_d_vec)), ref_delay) - half_window - abs(rho) - 1.0 hi = max(float(np.max(T_d_vec)), ref_delay) + half_window + abs(rho) + 1.0 n_resp = max(int(np.ceil((hi - lo) / SA_TIME_STEP)), 2) u, TOT_RESP, diagnostics = _response_vs_time(params, lo, hi, n_resp) # H_p is absorptive and H_dp refractive -- the same split the # Fresnel path makes into Gamma and eta. H_p = L * np.imag(TOT_RESP) H_dp = (2 * np.pi / lambda_p) * L * np.real(TOT_RESP) H_p_at = interp1d(u, H_p, kind="linear", bounds_error=False, fill_value=0.0) H_dp_at = interp1d(u, H_dp, kind="linear", bounds_error=False, fill_value=0.0) def energies(delays): """(energy difference, energy total) at each delay.""" # Window centred on the delay, +/- 5T, as specified. The # integrand peaks at tau = tau_d + rho, so the window is offset # by rho from the peak -- negligible while rho is small against # 5T, which holds for any sample thin enough for the walk-off # not to dominate. n_steps = max(int(np.ceil(2 * half_window / SA_TIME_STEP)), 2) offsets = np.linspace(-half_window, half_window, n_steps + 1) TAU = delays[:, np.newaxis] + offsets[np.newaxis, :] hp = H_p_at(TAU) hdp = H_dp_at(TAU) envelope = np.exp(-((rho - TAU + delays[:, np.newaxis]) ** 2) / T_ratio ** 2 - 2 * atten_X0 * hp) dP = (2 * atten_X0 * envelope * np.sqrt(2 * np.pi) * W ** 3 * X0 * (R_geom * hdp + SA_ABSORPTIVE_FACTOR(W) * hp / D_prop)) P = 0.5 * envelope * np.pi * W ** 2 return _trapz(dP, TAU, axis=1), _trapz(P, TAU, axis=1) dE, E = energies(T_d_vec) with np.errstate(invalid="ignore", divide="ignore"): DeltaEoE = np.where(E != 0, dE / E, 0.0) # Transmission is the energy total normalised to its value before # the pump arrives. Fitting takes that from the first delay point, # which is the measured scan's earliest; Simulation has no scan, so # it uses min(-3 rho, -3) tau_e -- the walk-off scale when that is # the larger, and three pulse widths otherwise, so a thin sample # (rho -> 0) still normalises away from the peak rather than on it. if params.run_mode == RUN_MODE_SIMULATION: E_ref = float(energies(np.array([ref_delay]))[1][0]) else: E_ref = float(E[0]) T_out = E / E_ref if E_ref != 0 else np.ones_like(E) tau_d_out = T_d_vec * tau_p_fs Delta_n = DeltaEoE / ((2 * np.pi / lambda_p) * L * np.sqrt(2 / np.e) * (w_0_p / w_0_e) * (2 / np.sqrt(np.pi))) # Same quantities as the Fresnel path reports, under this method's # names: H_dp is eta and H_p is Gamma. Taken over the response's own # time axis, which spans every integration window used, so the two # algorithms' values are directly comparable. result = dict(T=T_out, tau_d=tau_d_out, DeltaEoE=DeltaEoE, Delta_n=Delta_n, eta_peak=float(np.max(np.abs(H_dp))), Gamma_peak=float(np.max(np.abs(H_p))), diagnostics=diagnostics) if params.diagnostics: _diag_print("BD_Fresnel_func_sa - calculation time: " f"{time.time() - _t_start:g} s.") return result def BD_Fresnel_run(params: BDFresnelParams): """Runs whichever algorithm params.algorithm selects.""" if params.algorithm == ALGO_SEMI_ANALYTICAL: return BD_Fresnel_func_sa(params) return BD_Fresnel_func_ni(params) def _build_diagnostics(params, T1, T1_max, R_n, is_resp, NI_resp_diag, diag_responses, esa_diag, have_electronic, n_2el, alpha_2el, I_0_e): """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_2el, 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_2el here # while its four I_RESP branches all used 2*n_2el, 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_2el because the simulation applies none either. curves.append((2 * n_2el + 1j * alpha_2el) * I_0_e * 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). mpmath is imported here rather than at module level: it is needed only for the pump two-photon case (alpha_2d_e != 0), and importing it up front made an optional dependency fatal at startup for everyone. """ try: import mpmath except ImportError as exc: # pragma: no cover raise ImportError( "mpmath is required for the pump two-photon absorption term " "(alpha_2d_e != 0). Install it with 'pip install mpmath', or set " "alpha_2d_e to 0 to use the closed-form pump transmission." ) from exc return float(mpmath.re(mpmath.polylog(1.5, z))) def calc_beam_params(p: BDFresnelParams) -> BDFresnelParams: """ Recomputes the derived beam parameters (tau_e, tau, I_0_e, sigma_e, ng_e, ng, z_0, z_0_e, Tlin, Tlin_e, 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_e`/`tau` (the HW1/e values the physics engine actually consumes) are derived from tau_e_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_e, tau_e_FWHM, w_0_e, lambda_e, tau_p_FWHM, w_0_p, lambda_p, R_e, R_p, alpha_p, alpha_e, n_p, dndl_p, n_e, dndl_e, and alpha_2d_e do. Since `l` feeds sigma_e/Tlin_e/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_e = p.E_e * 1e-6 lambda_e = p.lambda_e * 1e-9 p.tau_e = p.tau_e_FWHM / (2 * np.sqrt(np.log(2))) # HW1/e of I [fs] tau_e = p.tau_e * 1e-15 w_0_e = p.w_0_e * 1e-6 lambda_p = p.lambda_p * 1e-9 p.tau_p = p.tau_p_FWHM / (2 * np.sqrt(np.log(2))) w_0_p = p.w_0_p * 1e-6 L = p.l * 1e-3 alpha_p = p.alpha_p * 100 n_p = p.n_p dn_dl = p.dndl_p * 1e6 R_e = p.R_e alpha_e = p.alpha_e * 100 n_e = p.n_e dn_dlp = p.dndl_e * 1e6 alpha_2d_e = p.alpha_2d_e * 1e-11 I_0_e = 2 * E_e / (np.pi ** 1.5 * w_0_e ** 2 * tau_e) * (1 - R_e) p.I_0_e = I_0_e p.sigma_e = alpha_e * L / 2 sigma_e = p.sigma_e sigma_e2 = I_0_e * alpha_2d_e * L / 2 p.ng_e = n_e - lambda_e * dn_dlp ng_e = p.ng_e p.ng_p = n_p - lambda_p * dn_dl ng_p = p.ng_p p.z_0_p = np.pi * w_0_p ** 2 / lambda_p p.z_0_e = np.pi * w_0_e ** 2 / lambda_e p.Tlin_p = np.exp(-alpha_p * L) if sigma_e2 == 0: p.Tlin_e = (1 - R_e) * np.exp(-2 * sigma_e) elif sigma_e == 0 and sigma_e2 != 0: p.Tlin_e = (1 - R_e) * (-_polylog_three_half(-2 * sigma_e2) / (2 * sigma_e2)) else: A1 = -1 + np.exp(2 * sigma_e) p.Tlin_e = (1 - R_e) * ( -sigma_e * _polylog_three_half(-(A1 * np.exp(-2 * sigma_e) * sigma_e2) / sigma_e) / (A1 * sigma_e2) ) p.rho = L / (tau_e * c) * (ng_p - ng_e) return p # ============================================================================= # inputs_valid.m (nested function inside BD_Fresnel_GUI.m) # ============================================================================= def inputs_valid(p: BDFresnelParams, require_data: bool = True) -> 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. require_data=False drops the last condition, for Simulation mode, which computes the signal without importing anything.""" return bool( p.E_e > 0 and p.tau_e_FWHM > 0 and p.w_0_e > 0 and p.lambda_e > 0 and p.tau_p_FWHM > 0 and p.w_0_p > 0 and p.lambda_p > 0 and p.n_e >= 1 and p.n_p >= 1 and 0 <= p.R_p < 1 and 0 <= p.R_e < 1 and p.alpha_p >= 0 and p.alpha_e >= 0 and p.d > 0 and p.l > 0 and (p.data_imported or not require_data) ) # ============================================================================= # save_settings.m / persistence (JSON in place of MATLAB's .mat file) # ============================================================================= def _mech_to_dicts(mechs): return [dict(name=m.name, param=list(m.param)) for m in mechs] def _mech_from_dicts(items): return [Mechanism(name=m["name"], param=list(m["param"])) for m in items] # Fields holding a list of Mechanism objects, which json cannot # serialize directly. _MECHANISM_LIST_FIELDS = ("mech", "mech_beam_deflection") # Version of the saved-settings key layout. It exists because the beam # subscripts were reassigned: the pump moved from _p to _e and the probe # from bare to _p, which left six probe field names spelled exactly like # the pump keys a pre-rename file used -- # # tau_p_FWHM, lambda_p, R_p, alpha_p, n_p, dndl_p # # all of which meant the PUMP before and mean the PROBE now. Loading # such a file by name alone would quietly install the pump's wavelength, # index, reflectivity, absorption and dispersion as the probe's, which # is far worse than falling back to defaults: every number would look # plausible and every result would be wrong. So a settings file is read # only if it carries a matching version, and is otherwise refused. SETTINGS_SCHEMA = 3 _SCHEMA_KEY = "settings_schema" def params_to_dict(p: BDFresnelParams) -> dict: d = dict(p.__dict__) for name in _MECHANISM_LIST_FIELDS: d[name] = _mech_to_dicts(getattr(p, name)) d[_SCHEMA_KEY] = SETTINGS_SCHEMA return d def params_from_dict(d: dict) -> BDFresnelParams: d = dict(d) mech_lists = {name: d.pop(name, None) for name in _MECHANISM_LIST_FIELDS} # Refuse a file from before the subscript reassignment rather than # misread it. See SETTINGS_SCHEMA: six probe field names are spelled # exactly like the pump keys such a file used, so the beams would be # silently crossed. An empty dict is allowed through as "nothing # saved yet". schema = d.pop(_SCHEMA_KEY, None) if d and schema != SETTINGS_SCHEMA: raise ValueError( f"settings file has schema {schema!r}, expected " f"{SETTINGS_SCHEMA}. The beam subscripts were reassigned " "(pump _p -> _e, probe bare -> _p), and six probe field " "names now match what were pump keys, so an older file " "cannot be read without crossing the two beams. Re-enter " "the parameters once and they will save in the new layout." ) # Any remaining unknown key is dropped and that field keeps its # default; say so rather than letting it pass silently. unknown = sorted(k for k in d if k not in BDFresnelParams.__dataclass_fields__) if unknown: print("bd_fresnel_core: ignoring unrecognised setting(s) " f"{', '.join(unknown)}; those parameters are at their " "defaults.") p = BDFresnelParams(**{k: v for k, v in d.items() if k in BDFresnelParams.__dataclass_fields__}) for name, items in mech_lists.items(): if items: setattr(p, name, _mech_from_dicts(items)) apply_mode_constraints(p) return p def _copy_mech(m: Mechanism) -> Mechanism: return Mechanism(name=m.name, param=list(m.param)) def apply_mode_constraints(p: BDFresnelParams) -> None: """Brings p into line with its mode without touching the set-aside beam-deflection state: an unknown mode falls back to beam deflection, and pump probe forces x_0 to 0 and empties any slot holding a mechanism the mode does not allow. Applied to every set of parameters loaded from disk, so a hand-edited or damaged settings file cannot put the program in an inconsistent state.""" if p.mode not in MODES: p.mode = MODE_BEAM_DEFLECTION if p.run_mode not in RUN_MODES: p.run_mode = RUN_MODE_FITTING if p.algorithm not in ALGORITHMS: p.algorithm = ALGO_FRESNEL if p.mode == MODE_PUMP_PROBE: p.x_0 = 0.0 for i, m in enumerate(p.mech): if not mechanism_allowed(m.name, p.mode): p.mech[i] = Mechanism() def set_mode(p: BDFresnelParams, mode: str): """Switches p to `mode`, returning (cleared, restored): the slot indices emptied on entering pump probe, and the ones refilled on leaving it. Both are empty when the mode does not change. Entering pump probe sets aside the current x_0 and mechanism slots, then sets x_0 = 0 and empties every slot the mode does not allow (the purely refractive ones); the rest stay where they are, parameters and all. Leaving it restores x_0, and puts each cleared mechanism back in its slot -- but only if that slot is still empty. A slot the user has since filled keeps its new mechanism, since that is the more recent choice. Mechanisms edited while in pump probe likewise keep their edits. """ if mode not in MODES: raise ValueError(f"unknown mode {mode!r}; expected one of {MODES}") if mode == p.mode: return [], [] cleared, restored = [], [] if mode == MODE_PUMP_PROBE: p.x_0_beam_deflection = p.x_0 p.mech_beam_deflection = [_copy_mech(m) for m in p.mech] p.mode = mode p.x_0 = 0.0 for i, m in enumerate(p.mech): if not mechanism_allowed(m.name, mode): p.mech[i] = Mechanism() cleared.append(i) else: p.mode = mode p.x_0 = p.x_0_beam_deflection for i, saved in enumerate(p.mech_beam_deflection[:len(p.mech)]): was_cleared = not mechanism_allowed(saved.name, MODE_PUMP_PROBE) if was_cleared and p.mech[i].name == NO_MECHANISM: p.mech[i] = _copy_mech(saved) restored.append(i) p.mech_beam_deflection = [] return cleared, restored 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)