Files
BD_Fresnel_GUI/bd_fresnel_core.py
T
2026-09-11 21:39:24 +00:00

1158 lines
47 KiB
Python

#!/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=<that same array>.
* 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)