From 45efc8239d4ad16e5df59c2744db8d3e5b22a406 Mon Sep 17 00:00:00 2001 From: manuel Date: Mon, 16 Nov 2026 17:40:21 +0000 Subject: [PATCH] Upload files to "/" --- CHANGELOG.md | 248 ++++++++++++++- bd_fresnel_core.py | 741 +++++++++++++++++++++++++++++++++++---------- bd_fresnel_gui.py | 367 +++++++++++++++------- last_settings.json | 165 ++++++++++ 4 files changed, 1245 insertions(+), 276 deletions(-) create mode 100644 last_settings.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 37689c1..31b8871 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,253 @@ All notable changes to BD Fresnel are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). -## [Unreleased] +## [3.0] - 2026-11-14 + +### Added + +- **Semi-analytical** algorithm, selectable from a third toggle in the + Operation mode box alongside **Fresnel propagation**: + - Instead of propagating the exit field to the detector by FFT, it + uses closed-form expressions for the power difference and total at + the detector, already integrated over the detector plane. Only an + integral over time at each delay remains. + - The time window runs +/- 5T about each delay, where T = tau_p/tau_e. + - Transmission is the energy total normalised to its value before the + pump arrives: the first delay point when fitting, and + min(-3 rho, -3) tau_e when simulating, so a thin sample with + rho -> 0 still normalises away from the peak. + - `X_num` and `X_max` are disabled in this mode: the expressions are + already integrated over space, so there is no spatial grid. + - Applies to both measurement modes. In pump probe the probe is + centred, x_0 = 0, so the deflection term vanishes identically and + the transmission alone is calculated. + - Both algorithms are kept so results can be compared. Switching + discards the current result, which belongs to the other method. + - The algorithm is saved with the other settings and recorded in the + parameter log. + - The absorptive term in the deflection expression carries a + PROVISIONAL coefficient, `SA_ABSORPTIVE_FACTOR`. As derived, that + term matched neither the sign nor the magnitude of the Fresnel + result: a purely absorptive mechanism disagreed by a factor of + about -69, with correlation exactly -1. Dividing by + D = d / (pi w_0_p^2 / lambda_p) = d / z_0_p accounts for the distance and + wavelength dependence exactly, and is independent of sample + thickness at constant alpha_2_exp*l; the remaining -1/(1 + 2W^2) was + measured against the Fresnel path rather than derived. With it the + two methods agree to 0.5% for mechanisms with a refractive part and + 4.5% for purely absorptive ones. It is isolated in one function + pending a corrected derivation. + +- The parameter log's `Calculated Parameters (pump)` section reports + `sigma_e`, the normalised pump linear absorption `alpha_e * L / 2`. + It sits next to `T_lin`, which restates it: with no pump two-photon + absorption `T_lin = (1 - R_p) exp(-2 sigma_e)`. Read from the + parameters rather than the result, so it is reported for either + algorithm. + +- The `Other` panel and the parameter log's `Other` section both report + `eta (peak)` and `Gamma (peak)`, the largest nonlinear phase and + absorption exponent anywhere on the grid, from whichever algorithm + produced the result. These are the only readouts in those panels that + come from the result rather than from the parameters, since they are + peaks over the whole (T, T_d) grid and cannot be had without running + the calculation. They therefore show `--` until a Fit or Simulate + completes, and return to `--` whenever that result is discarded, so a + stale phase is never displayed beside freshly edited parameters. + `eta (peak)` is the yardstick for the semi-analytical algorithm's + validity: its `dP` is first order in the response while Fresnel + propagation keeps every order, so the two agree only while the phase + is small. 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. Holding `eta (peak)` + fixed, the agreement is unaffected by sample thickness (0.05 to + 2 mm), by walk-off (`rho` 0.04 to 1.7) and by pump absorption + (`sigma_e` 0 to 10), so this one number sets the regime. Both + algorithms report it to within 2e-5 of each other. + +### Changed + +- **Both beams are now explicitly subscripted: the pump carries `_e` + (excitation) and the probe carries `_p`.** This restores the + convention the original MATLAB used, which the Python port had + partly inverted (`_p` for the pump) and partly dropped (no suffix + for the probe). No beam quantity is unsubscripted any more; the only + unsuffixed parameters left are the ones belonging to neither beam -- + the sampling grid, the sample geometry (`l`, `d`, `shift`), the + relative offset `x_0`, and the walk-off `rho`. + + | pump: was | now | | probe: was | now | + |-----|-----|-|-----|-----| + | `E_p` | `E_e` | | `tau_FWHM` | `tau_p_FWHM` | + | `tau_p_FWHM` | `tau_e_FWHM` | | `w_0` | `w_0_p` | + | `w_0p` | `w_0_e` | | `lambda_` | `lambda_p` | + | `lambda_p` | `lambda_e` | | `R` | `R_p` | + | `R_p` | `R_e` | | `alpha` | `alpha_p` | + | `alpha_p` | `alpha_e` | | `n` | `n_p` | + | `n_p` | `n_e` | | `dndl` | `dndl_p` | + | `dndl_p` | `dndl_e` | | `tau` | `tau_p` | + | `alpha_2d` | `alpha_2d_e` | | `ng` | `ng_p` | + | `tau_p` | `tau_e` | | `z_0` | `z_0_p` | + | `sigma_p` | `sigma_e` | | `Tlin` | `Tlin_p` | + | `I_0_p` | `I_0_e` | | | | + | `ng_p` | `ng_e` | | | | + | `z_0_p` | `z_0_e` | | | | + | `Tlin_p` | `Tlin_e` | | | | + | `sigma_p2` / `sigma_p20` | `sigma_e2` / `sigma_e20` | | | | + | `a_p_0`, `W_0_p`, `I_p_pulse` | `a_e_0`, `W_0_e`, `I_e_pulse` | | | | + + Note that six probe names -- `tau_p_FWHM`, `lambda_p`, `R_p`, + `alpha_p`, `n_p`, `dndl_p` -- are spelled exactly like what were + **pump** names before this release. Reading an old log or settings + file alongside a new one needs care; see the settings note below for + how the program itself is protected. + + The pump pass renamed 389 identifier occurrences textually; the + probe pass was done by rewriting 116 exact AST node positions + instead, because `n`, `R`, `alpha` and `tau` are overloaded in this + codebase (lambda parameters, the author's initials in the copyright + line, the semi-analytical formula's geometric `R`, a diagnostics + dict key) and no text pattern distinguishes them. + + | was | now | | was | now | + |-----|-----|-|-----|-----| + | `E_p` | `E_e` | | `tau_p` | `tau_e` | + | `tau_p_FWHM` | `tau_e_FWHM` | | `sigma_p` | `sigma_e` | + | `w_0p` | `w_0_e` | | `I_0_p` | `I_0_e` | + | `lambda_p` | `lambda_e` | | `ng_p` | `ng_e` | + | `R_p` | `R_e` | | `z_0_p` | `z_0_e` | + | `alpha_p` | `alpha_e` | | `Tlin_p` | `Tlin_e` | + | `n_p` | `n_e` | | `sigma_p2` | `sigma_e2` | + | `dndl_p` | `dndl_e` | | `sigma_p20` | `sigma_e20` | + | `alpha_2d` | `alpha_2d_e` | | `a_p_0` | `a_e_0` | + + `w_0p` gains the separating underscore it was missing, so the field + name finally matches the variable that held it (`w_0_p`) and its + siblings `z_0_e` and `I_0_e`. `alpha_2d_e` keeps the `d` for + degenerate. + +- **The Electronic mechanism's parameters are renamed `alpha_2e` -> + `alpha_2el` and `n_2e` -> `n_2el`**, since their `e` meant + *electronic* and would otherwise collide with `_e` for excitation -- + the pump's degenerate two-photon coefficient would have wanted the + name `alpha_2e`, which was taken. `_e` now means excitation and + nothing else. + +- `BD_3_level_triplet`, `I_e_func` and `excite_prop` needed no + renaming at all: transliterated from the MATLAB, they already used + `_e` for the pump and `_p` for the probe, so `n_g_p`, `v_p` and + `I_p` inside them were correct all along. With both beams now + subscribed to that convention, the whole file reads against the + MATLAB without translation. + +- **`last_settings.json` written by an earlier version is now refused + rather than misread.** Saved settings carry a `settings_schema` + stamp, and a file without the current one is rejected with a message + explaining why. This is not housekeeping: because six probe field + names are spelled exactly like former pump keys, loading an old file + by name alone would have installed the pump's wavelength, index, + reflectivity, absorption and dispersion as the *probe's* -- every + number plausible, every result wrong. Re-enter the parameters once + and they save in the new layout. Any other unrecognised key is still + dropped with a note on stderr. + +- Log and panel labels follow their fields on both sides: `n_g_e`, + `sigma_e`, `T_lin_e`, `z_0_e`, `I_0_e` for the pump and `n_g_p`, + `T_lin_p`, `z_0_p` for the probe, with the beam parameters and + material blocks likewise. The GUI's pump calculated-parameters panel + also gains a `sigma_e` readout, which it had not displayed before. + +- `T_lin_p` and `T_lin_e` are labelled `T_lin_p (transmission)` and + `T_lin_e (transmission)` in both the panel and the log, so the + quantity is named and not just abbreviated. The log's value column + moved from 25 to 29 to fit them, and the panel's label column from 20 + to 23 characters -- which also squares up `z_0_p (Rayleigh range)`, + `z_0_e (Rayleigh range)` and `I_0_e (peak irradiance)`, all of which + had been overrunning the old 20 and pushing their own values out of + line. + +- The rename is numerically inert: across 8 mechanism types x 2 + algorithms x 3 pump-absorption configurations (49 cases, 3275 + values), `DeltaEoE`, `T`, `Delta_n`, `eta_peak` and `Gamma_peak` are + bit-identical to the pre-rename code, and `pyflakes` reports zero + warnings before and after. + +- Transmission y-axis tick labels are limited to three significant + digits, so "99.75" reads "99.8". The count is a floor rather than a + cap: a shallow scan spanning a few hundredths of a percent would + round every tick to "100", so digits are added only where that would + happen. The deflection axis is unaffected. + +- The reference list in the README and the parameter log follows Optica + style: every author listed, initials first, abbreviated journal, + volume, full page range, year. Author lists and page ranges were + checked against the published papers. +- The duplicate supplementary-material citation is dropped, leaving two + references. +- The parameter log is written as UTF-8. The citations use typographic + quotes and an en dash, which the locale's encoding cannot always + represent. + +### Fixed + +- The instantaneous (Electronic) response for a sample with both + walk-off and pump absorption is evaluated through the scaled + complementary error function `erfcx` instead of the form in + `BD_Fresnel_func_ni.m`. That form multiplied `exp(sigma_e^2/rho^2 + + 2 sigma_e u/rho)` by a difference of error functions falling to zero, + so the product was lost to cancellation well before it overflowed: + at `rho = 0.4336` (l = 0.5 mm) it was already wrong over 8.6% of the + delay axis at `sigma_e = 2.5` (alpha_e = 100 cm^-1), **returning + exactly 0.0 with no NaN to signal it**, and returned NaN above + `sigma_e = 3`. The usable ceiling on `alpha_e` for an Electronic + mechanism at that thickness was therefore about 60 cm^-1, not the + ~120 where NaN first appeared. The rearrangement is algebraic, with + every surviving exponent non-positive; it reproduces the original + evaluated at 600 decimal digits to 1e-16..3e-13 relative over + `sigma_e` = 0.25 to 10 and `u` = -3 to 18, both where the original + works and where it does not. +- Pump absorption is applied to non-instantaneous mechanisms when the + walk-off is exactly zero. Substituting `T1 = (T+T_d) - rho + + rho*zeta` shows the `rho != 0` branch to be a depth average over + `atten_fac`, whose `rho -> 0` limit is the response at one instant + times the *mean* of `atten_fac`; the original used the bare response. + The dropped factor is `(1 - exp(-2 sigma_e))/(2 sigma_e)` for linear + pump absorption, so the response was previously **independent of + `alpha_e` altogether** in this case -- identical at `alpha_e` = 0 and + 200 cm^-1. It was 1.27x too large at `alpha_e` = 10 cm^-1 and + l = 0.5 mm, and 10x at 200 cm^-1. The two branches now agree to nine + digits across `rho = 0`. This affects only samples with `ng_p` exactly + equal to `ng_e` (for example no dispersion entered at either + wavelength) *and* non-zero pump absorption; with `alpha_e = alpha_2d_e + = 0` the mean is exactly 1 and results are bit-identical to before. +- Pump absorption through the sample depth, `atten_fac`, is computed + from the closed-form solution of + `dI_e/dz = -alpha_e I_e - alpha_2d_e I_e^2` rather than the two-branch + expression carried over from `BD_Fresnel_func_ni.m`. That expression's + pump two-photon branch, `sqrt((B1 B2)/sigma_e)`, failed three ways: it + did not reduce to its own `sigma_e2 == 0` branch as `alpha_2d_e -> 0` + (it decayed at 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`. The net effect was that **every run + combining a non-zero `alpha_2d_e` with a non-instantaneous mechanism + returned NaN at every delay** -- pump two-photon absorption worked + only for the Electronic mechanism, which does not use `atten_fac`. + Dropping the stray square root recovers that expression as the + linearisation of the exact one in `sigma_e20`, which is how the + intent was identified. Results for `alpha_2d_e = 0` are bit-identical + to before; the new form agrees with numerical integration of the + pump propagation equation to 2e-12 relative over `sigma_e` and + `sigma_e20` from 0 to 20, including both limits. +- A negative `alpha_2d_e` large enough to make the pump diverge inside + the sample (two-photon gain, no finite depth average) is now refused + with a message naming the largest `|alpha_2d_e|` that works for the + current thickness and pump irradiance, rather than silently returning + a meaningless attenuation of order 1e12. +- `mpmath` is imported only where it is used, in the pump two-photon + absorption term. Importing it at module level made an optional + dependency fatal at startup, so the program would not run at all + without it. If that term is ever reached without mpmath installed, + the error now says which package is missing and why. ## [2.6] - 2026-09-30 diff --git a/bd_fresnel_core.py b/bd_fresnel_core.py index e7eb126..22c3686 100644 --- a/bd_fresnel_core.py +++ b/bd_fresnel_core.py @@ -94,8 +94,9 @@ NOTES ON THE MATLAB -> PYTHON TRANSLATION numpy.heaviside(x, 0.5). """ -__version__ = "2.6" +__version__ = "3.0" +import copy import time import datetime @@ -105,10 +106,9 @@ 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 scipy.special import erf, erfcx 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 @@ -137,6 +137,30 @@ 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.""" @@ -196,6 +220,53 @@ 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 @@ -218,7 +289,7 @@ def mechanism_names_for_mode(mode: str) -> List[str]: MECHANISM_PARAM_SPECS = { "None (both)": [], "Electronic (both)": [ - ("alpha_2e", "e-11 m/W"), ("n_2e", "e-19 m^2/W"), + ("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"), @@ -259,47 +330,47 @@ class BDFresnelParams: 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] + 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_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] + 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_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] + 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: 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] + 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_0p] + x_0: float = 0.5 # pump-probe x displacement [w_0_e] # --- 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 + 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: 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) + 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 @@ -343,6 +414,8 @@ class BDFresnelParams: 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 @@ -399,13 +472,13 @@ def excite_prop(t, y, z, I_0_e, v_e, v_p, tau_e, E_photon, # 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): +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_p - t_exp_f = tau_exp_f / tau_p + 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) @@ -417,12 +490,12 @@ def BD_exp_rise_decay(alpha_2_exp, n_2_exp, tau_exp_r, tau_exp_f, tau_p, T1): return R_exp -def BD_librational(n_2l, omega_0, omega_std, tau_lf, tau_p, T1): +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_p - omega_stdn = omega_std * tau_p - tau_lfn = tau_lf / tau_p + 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) @@ -452,11 +525,11 @@ def BD_librational(n_2l, omega_0, omega_std, tau_lf, tau_p, T1): return R_l_interp -def BD_vibrational(n_2v, w_0v, tau_vf, tau_p, T1): +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_p - tau_vfn = tau_vf / tau_p + 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) @@ -501,6 +574,13 @@ def BD_3_level_triplet(alpha_2_e, I_0_e, lambda_e, n_g_e, tau_e, w_0_e, 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 @@ -647,7 +727,7 @@ def _build_esa_time_grid(F, x, y, tau_d, w_0_e, X0, n_t_in): # BD_Fresnel_func_ni.m # ============================================================================= -def BD_Fresnel_func_ni(params: BDFresnelParams): +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 @@ -660,27 +740,27 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): _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_0p * 1e-6 - - lambda_ = params.lambda_ * 1e-9 - tau = params.tau * 1e-15 - w_0 = params.w_0 * 1e-6 + w_0_p = params.w_0_p * 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 + alpha_p = params.alpha_p * 100 + alpha_2d_e = params.alpha_2d_e * 1e-11 - sigma_p = params.sigma_p - I_0_p = params.I_0_p + sigma_e = params.sigma_e + I_0_e = params.I_0_e + ng_e = params.ng_e ng_p = params.ng_p - ng = params.ng rho = params.rho @@ -689,12 +769,12 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): 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 + sigma = alpha_p * L / 2 - t = tau / tau_p - W_0_p = w_0_p / w_0 - D = d / w_0 - LAMBDA = lambda_ / w_0 + 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) @@ -732,8 +812,8 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): 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 + 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) @@ -750,7 +830,7 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): I_RESP = 0.0 a_ESA = 1.0 have_electronic = False - n_2e = alpha_2e = 0.0 + n_2el = alpha_2el = 0.0 rho_min = 1e-4 # Per-mechanism response-function plots. The original drew these @@ -790,37 +870,67 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): elif name == "Electronic (both)": have_electronic = True - alpha_2e = p[0] * 1e-11 - n_2e = p[1] * 1e-19 + alpha_2el = p[0] * 1e-11 + n_2el = 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) + 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_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 < 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_p == 0: + elif rho != 0 and sigma_e == 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) + 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_p * (2 * n_2e + 1j * alpha_2e) * ((A1 * A2) - (A3 * A4) * np.sqrt(np.pi)) / (2 * rho ** 2) + 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_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 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_p, T1) + 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)": @@ -828,7 +938,7 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): 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) + 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) @@ -837,14 +947,14 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): 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) + 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_p, T1) + 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)": @@ -862,11 +972,11 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): 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, + 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_p, X_vec * w_0, Y_vec * w_0, + 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: @@ -876,14 +986,14 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): 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) + 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_p, T1) + 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)": @@ -891,7 +1001,7 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): 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) + 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 --- @@ -902,10 +1012,10 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): 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 + 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]): @@ -913,7 +1023,7 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): # 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 + 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 @@ -923,17 +1033,65 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): Resp_tot_interp = interp1d(T1, Resp_tot, kind="linear", bounds_error=False, fill_value="extrapolate") - sigma_p20 = I_0_p * alpha_2d * L / 2 + sigma_e20 = I_0_e * alpha_2d_e * 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) + # 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: - 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) + 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 @@ -947,7 +1105,18 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): 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) + # 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 @@ -955,13 +1124,32 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): # 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) + 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_p_0 ** 2) * CHI_RESP) * a_ESA) + 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 @@ -983,24 +1171,196 @@ def BD_Fresnel_func_ni(params: BDFresnelParams): # --- package output --- T_out = E_tot / E_tot[0] - tau_d_out = T_d_vec * tau_p * 1e15 + tau_d_out = T_d_vec * tau_e * 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))) + 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_2e, alpha_2e, I_0_p)) + 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_2e, alpha_2e, I_0_p): + 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. @@ -1031,16 +1391,16 @@ def _build_diagnostics(params, T1, T1_max, R_n, is_resp, NI_resp_diag, 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 + # 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_2e here - # while its four I_RESP branches all used 2*n_2e, so 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_2e because the simulation applies none either. - curves.append((2 * n_2e + 1j * alpha_2e) * I_0_p * np.exp(-T1 ** 2)) + # 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}" @@ -1067,14 +1427,27 @@ def _polylog_three_half(z: float) -> float: 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).""" + 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_p, tau, I_0_p, sigma_p, - ng_p, ng, z_0, z_0_p, Tlin, Tlin_p, rho) from the raw parameters, + 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). @@ -1089,8 +1462,8 @@ def calc_beam_params(p: BDFresnelParams) -> BDFresnelParams: 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/ + 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 @@ -1100,66 +1473,67 @@ def calc_beam_params(p: BDFresnelParams) -> BDFresnelParams: 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 + 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_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 + 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.lambda_ * 1e-9 - p.tau = p.tau_FWHM / (2 * np.sqrt(np.log(2))) - w_0 = p.w_0 * 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.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 + dn_dl = p.dndl_p * 1e6 - 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 + 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 - p.sigma_p = alpha_p * L / 2 - sigma_p = p.sigma_p + 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 - sigma_p2 = I_0_p * alpha_2d * L / 2 + p.sigma_e = alpha_e * L / 2 + sigma_e = p.sigma_e - p.ng_p = n_p - lambda_p * dn_dlp + 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.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.z_0_e = np.pi * w_0_e ** 2 / lambda_e - p.Tlin = np.exp(-alpha * L) + p.Tlin_p = np.exp(-alpha_p * 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)) + 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_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) + 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_p * c) * (ng - ng_p) + p.rho = L / (tau_e * c) * (ng_p - ng_e) return p @@ -1176,19 +1550,19 @@ def inputs_valid(p: BDFresnelParams, require_data: bool = True) -> bool: require_data=False drops the last condition, for Simulation mode, which computes the signal without importing anything.""" return bool( - p.E_p > 0 + 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_0p > 0 + and p.w_0_p > 0 and p.lambda_p > 0 - and p.tau_FWHM > 0 - and p.w_0 > 0 - and p.lambda_ > 0 + and p.n_e >= 1 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 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) @@ -1211,17 +1585,56 @@ def _mech_from_dicts(items): # 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: @@ -1245,6 +1658,8 @@ def apply_mode_constraints(p: BDFresnelParams) -> None: 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): diff --git a/bd_fresnel_gui.py b/bd_fresnel_gui.py index 0e417fe..fa76714 100644 --- a/bd_fresnel_gui.py +++ b/bd_fresnel_gui.py @@ -61,13 +61,15 @@ from bd_fresnel_core import ( MECHANISM_NAMES, calc_beam_params, inputs_valid, - BD_Fresnel_func_ni, + BD_Fresnel_run, save_settings, load_settings, MODE_BEAM_DEFLECTION, MODE_PUMP_PROBE, RUN_MODE_FITTING, RUN_MODE_SIMULATION, + ALGO_FRESNEL, + ALGO_SEMI_ANALYTICAL, mechanism_names_for_mode, set_mode, ) @@ -81,9 +83,9 @@ SETTINGS_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "last_s # bd_fresnel_core.calc_beam_params for why (faithfully preserved from # the original, not a translation gap). CALC_BEAM_PARAMS_FIELDS = { - "E_p", "tau_p_FWHM", "w_0p", "lambda_p", - "tau_FWHM", "w_0", "lambda_", - "R_p", "R", "alpha", "alpha_p", "n", "dndl", "n_p", "dndl_p", "alpha_2d", + "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", "alpha_2d_e", } # (field, label, unit, abs_on_entry, log_name) -- mirrors each @@ -95,34 +97,34 @@ CALC_BEAM_PARAMS_FIELDS = { # validation there is permissive -- only NaN is actually rejected at # entry, faithfully preserved). PUMP_FIELDS = [ - ("E_p", "E_p (pump energy)", "uJ", True), - ("tau_p_FWHM", "tau_p_FWHM", "fs", True), - ("w_0p", "w_0p (pump waist)", "um", True), - ("lambda_p", "lambda_p (pump)", "nm", True), + ("E_e", "E_e (pump energy)", "uJ", True), + ("tau_e_FWHM", "tau_e_FWHM", "fs", True), + ("w_0_e", "w_0_e (pump waist)", "um", True), + ("lambda_e", "lambda_e (pump)", "nm", True), ] PROBE_FIELDS = [ - ("tau_FWHM", "tau_FWHM", "fs", True), - ("w_0", "w_0 (probe waist)", "um", True), - ("lambda_", "lambda (probe)", "nm", True), + ("tau_p_FWHM", "tau_p_FWHM", "fs", True), + ("w_0_p", "w_0_p (probe waist)", "um", True), + ("lambda_p", "lambda_p (probe)", "nm", True), ] MAT_PUMP_FIELDS = [ + ("R_e", "R_e (reflectivity)", "0-1", True), + ("alpha_e", "alpha_e (absorption)", "cm^-1", True), + ("n_e", "n_e (index)", "", True), + ("dndl_e", "dndl_e (dispersion)", "um^-1", False), + ("alpha_2d_e", "alpha_2d_e (2PA)", "e-11 m/W", False), +] +MAT_PROBE_FIELDS = [ ("R_p", "R_p (reflectivity)", "0-1", True), ("alpha_p", "alpha_p (absorption)", "cm^-1", True), ("n_p", "n_p (index)", "", True), ("dndl_p", "dndl_p (dispersion)", "um^-1", False), - ("alpha_2d", "alpha_2d (2PA)", "e-11 m/W", False), -] -MAT_PROBE_FIELDS = [ - ("R", "R (reflectivity)", "0-1", True), - ("alpha", "alpha (absorption)", "cm^-1", True), - ("n", "n (index)", "", True), - ("dndl", "dndl (dispersion)", "um^-1", False), ] SYSTEM_FIELDS = [ ("l", "l (thickness)", "mm", True), ("d", "d (sample->detector)", "cm", True), ("shift", "shift (delay zero)", "fs", False), - ("x_0", "x_0 (pump-probe offset)", "w_0p", False), + ("x_0", "x_0 (pump-probe offset)", "w_0_e", False), ] # Escape sequences accepted in the Delimiter field. A literal tab @@ -155,12 +157,12 @@ def describe_delimiter(text: str) -> str: # scan's delay range and the fields are disabled. SIM_FIELDS = [ ("X_num", "X_num (spatial pts)", "points", "int"), - ("X_max", "X_max (spatial extent)", "w_0", "float"), + ("X_max", "X_max (spatial extent)", "w_0_p", "float"), ("T_num", "T_num (time pts)", "points", "int"), - ("T_max", "T_max (time extent)", "tau_p", "float"), + ("T_max", "T_max (time extent)", "tau_e", "float"), ("T_d_num", "T_d_num (delay pts)", "points", "int"), - ("T_d_min", "T_d_min (delay start)", "tau_p", "signed"), - ("T_d_max", "T_d_max (delay end)", "tau_p", "signed"), + ("T_d_min", "T_d_min (delay start)", "tau_e", "signed"), + ("T_d_max", "T_d_max (delay end)", "tau_e", "signed"), ] # The numeric parameter boxes, in panel order. Each entry is @@ -208,6 +210,15 @@ RUN_MODE_CHOICES = [ ] RUN_MODE_LABELS = dict(RUN_MODE_CHOICES) +# The algorithm toggle, drawn below the run-mode one. Fresnel +# propagation is the original method; Semi-analytical uses closed-form +# detector expressions and integrates only over time. +ALGO_CHOICES = [ + (ALGO_FRESNEL, "Fresnel propagation"), + (ALGO_SEMI_ANALYTICAL, "Semi-analytical"), +] +ALGO_LABELS = dict(ALGO_CHOICES) + # Which column of the imported file feeds each quantity. 1-based, in # the order they are shown in the "Data columns" box. DATA_COLUMN_FIELDS = [ @@ -286,11 +297,19 @@ class LabeledEntry(ttk.Frame): class LabeledStatic(ttk.Frame): - """Read-only calculated-value display (e.g. rho, I_0_p).""" + """Read-only calculated-value display (e.g. rho, I_0_e).""" + + # Widest label in use is "I_0_e (peak irradiance)" at 23 + # characters. The width is a minimum request, not a clip, so a + # label longer than this does not truncate -- it pushes its own + # value right and breaks the column alignment, which is what + # happened when the T_lin labels gained "(transmission)". + LABEL_WIDTH = 23 def __init__(self, parent, label): super().__init__(parent) - ttk.Label(self, text=label, width=20, anchor="w").pack(side="left") + ttk.Label(self, text=label, width=self.LABEL_WIDTH, + anchor="w").pack(side="left") self.var = tk.StringVar(value="--") ttk.Label(self, textvariable=self.var, width=16, anchor="w", foreground="black").pack(side="left") @@ -398,7 +417,7 @@ class BDFresnelApp(tk.Tk): self.params = self._load_or_default_params() self.data = None # dict with tau_d, tau_d_shifted, T, DeltaEoE, Delta_n - self.fit = None # dict, output of BD_Fresnel_func_ni + self.fit = None # dict, output of BD_Fresnel_run # The file loaded this session, if any. A mode change re-reads # it, since the two modes need different columns. Kept even if # that re-read fails, so switching back can load it again. @@ -564,6 +583,10 @@ class BDFresnelApp(tk.Tk): self._run_mode_buttons = self._build_toggle_row( sec, RUN_MODE_CHOICES, self.run_mode_var, self._on_run_mode_change, pady=(3, 0)) + self.algorithm_var = tk.StringVar(value=self.params.algorithm) + self._algorithm_buttons = self._build_toggle_row( + sec, ALGO_CHOICES, self.algorithm_var, self._on_algorithm_change, + pady=(3, 0)) sec = add_section(parent, "Data columns") for name, label in DATA_COLUMN_FIELDS: @@ -619,26 +642,42 @@ class BDFresnelApp(tk.Tk): command=self._on_diagnostics_change).pack(anchor="w") sec = add_section(parent, "Calculated Parameters (probe)") - self.calc_ng = LabeledStatic(sec, "n_g (group index)") - self.calc_ng.pack(fill="x", pady=1) - self.calc_Tlin = LabeledStatic(sec, "T_lin") - self.calc_Tlin.pack(fill="x", pady=1) - self.calc_z0 = LabeledStatic(sec, "z_0 (Rayleigh range)") - self.calc_z0.pack(fill="x", pady=1) + self.calc_ng_p = LabeledStatic(sec, "n_g_p (group index)") + self.calc_ng_p.pack(fill="x", pady=1) + self.calc_Tlin_p = LabeledStatic(sec, "T_lin_p (transmission)") + self.calc_Tlin_p.pack(fill="x", pady=1) + self.calc_z0_p = LabeledStatic(sec, "z_0_p (Rayleigh range)") + self.calc_z0_p.pack(fill="x", pady=1) + # Pump side is subscripted _e, probe side bare, matching the + # field names and the log. sec = add_section(parent, "Calculated Parameters (pump)") - self.calc_ngp = LabeledStatic(sec, "n_g (group index)") - self.calc_ngp.pack(fill="x", pady=1) - self.calc_Tlinp = LabeledStatic(sec, "T_lin") - self.calc_Tlinp.pack(fill="x", pady=1) - self.calc_z0p = LabeledStatic(sec, "z_0 (Rayleigh range)") - self.calc_z0p.pack(fill="x", pady=1) - self.calc_I0p = LabeledStatic(sec, "I_0 (peak irradiance)") - self.calc_I0p.pack(fill="x", pady=1) + self.calc_ng_e = LabeledStatic(sec, "n_g_e (group index)") + self.calc_ng_e.pack(fill="x", pady=1) + self.calc_sigma_e = LabeledStatic(sec, "sigma_e (absorption)") + self.calc_sigma_e.pack(fill="x", pady=1) + self.calc_Tlin_e = LabeledStatic(sec, "T_lin_e (transmission)") + self.calc_Tlin_e.pack(fill="x", pady=1) + self.calc_z0_e = LabeledStatic(sec, "z_0_e (Rayleigh range)") + self.calc_z0_e.pack(fill="x", pady=1) + self.calc_I0_e = LabeledStatic(sec, "I_0_e (peak irradiance)") + self.calc_I0_e.pack(fill="x", pady=1) sec = add_section(parent, "Other") self.calc_rho = LabeledStatic(sec, "rho (GVM parameter)") self.calc_rho.pack(fill="x", pady=1) + # Unlike every other value in these panels, which is derived + # from the parameters alone and so updates as they are typed, + # eta and Gamma come from the result: they are peaks over the + # whole (T, T_d) grid, which there is no way to get without + # running the calculation. They therefore read "--" until a Fit + # or Simulate completes, and go back to "--" whenever that + # result is discarded, so a stale phase is never shown beside + # freshly edited parameters. See _refresh_result_values. + self.calc_eta = LabeledStatic(sec, "eta (peak)") + self.calc_eta.pack(fill="x", pady=1) + self.calc_Gamma = LabeledStatic(sec, "Gamma (peak)") + self.calc_Gamma.pack(fill="x", pady=1) # ------------------------------------------------------------------ # Field / state synchronization @@ -686,6 +725,13 @@ class BDFresnelApp(tk.Tk): for name in ("T_d_min", "T_d_max"): self._field_widgets[name].set_enabled(simulating) + # The semi-analytical expressions are already integrated over + # the detector plane, so there is no spatial grid to size. + for name in ("X_num", "X_max"): + self._field_widgets[name].set_enabled( + self.params.algorithm != ALGO_SEMI_ANALYTICAL) + self.algorithm_var.set(self.params.algorithm) + self.import_button.config(state="disabled" if simulating else "normal") self.fit_button.config(text=self.run_action_label) @@ -703,7 +749,7 @@ class BDFresnelApp(tk.Tk): row = ttk.Frame(parent) row.pack(anchor="w", pady=pady) width = max(len(label) - for group in (MODE_CHOICES, RUN_MODE_CHOICES) + for group in (MODE_CHOICES, RUN_MODE_CHOICES, ALGO_CHOICES) for _, label in group) buttons = [] for value, label in choices: @@ -752,6 +798,28 @@ class BDFresnelApp(tk.Tk): def _on_run_mode_change(self): self._set_run_mode(self.run_mode_var.get()) + def _on_algorithm_change(self): + self._set_algorithm(self.algorithm_var.get()) + + def _set_algorithm(self, algorithm): + """Switches between Fresnel propagation and the semi-analytical + expressions. Any result on screen is discarded: it was computed + by the other method, and the point of having both is to compare + them deliberately rather than to leave one mislabelled.""" + if algorithm == self.params.algorithm: + return # Tk fires on every click, re-selection included + self.params.algorithm = algorithm + self.params.data_fit = False + self.fit = None + self._refresh_param_fields_from_state() + self._refresh_plots() + self._refresh_diagnostics() + self._update_action_buttons() + self._save_settings() + message = f"Algorithm: {ALGO_LABELS[algorithm]}." + self.status_var.set(message) + print(f"bd_fresnel_gui: {message}") + def _set_run_mode(self, run_mode): """Switches between fitting an imported scan and simulating without one. Any result on screen is discarded: a fit describes @@ -818,7 +886,7 @@ class BDFresnelApp(tk.Tk): def _set_mode_buttons_enabled(self, enabled: bool): """The fit runs on a worker thread that reads self.params throughout, so neither mode must change underneath it.""" - for b in self._mode_buttons + self._run_mode_buttons: + for b in self._mode_buttons + self._run_mode_buttons + self._algorithm_buttons: b.state(["!disabled"] if enabled else ["disabled"]) def _on_field_change(self, field_name): @@ -973,13 +1041,14 @@ class BDFresnelApp(tk.Tk): def _recalc_beam_params(self, refresh_display=False): calc_beam_params(self.params) if refresh_display: - self.calc_ng.set(f"{self.params.ng:.3f}") - self.calc_Tlin.set(f"{self.params.Tlin:.3f}") - self.calc_z0.set(f"{self.params.z_0 * 1e3:.3f} mm") - self.calc_ngp.set(f"{self.params.ng_p:.3f}") - self.calc_Tlinp.set(f"{self.params.Tlin_p:.3f}") - self.calc_z0p.set(f"{self.params.z_0_p * 1e3:.3f} mm") - self.calc_I0p.set(f"{self.params.I_0_p * 1e-13:.3f} GW/cm^2") + self.calc_ng_p.set(f"{self.params.ng_p:.3f}") + self.calc_Tlin_p.set(f"{self.params.Tlin_p:.3f}") + self.calc_z0_p.set(f"{self.params.z_0_p * 1e3:.3f} mm") + self.calc_ng_e.set(f"{self.params.ng_e:.3f}") + self.calc_sigma_e.set(f"{self.params.sigma_e:.3f}") + self.calc_Tlin_e.set(f"{self.params.Tlin_e:.3f}") + self.calc_z0_e.set(f"{self.params.z_0_e * 1e3:.3f} mm") + self.calc_I0_e.set(f"{self.params.I_0_e * 1e-13:.3f} GW/cm^2") self.calc_rho.set(f"{self.params.rho:.3f}") def _update_fit_button_state(self): @@ -1003,6 +1072,23 @@ class BDFresnelApp(tk.Tk): def _update_action_buttons(self): self._update_fit_button_state() self._update_export_button_state() + self._refresh_result_values() + + def _refresh_result_values(self): + """Fills the result-derived readouts in the "Other" panel, or + blanks them when there is no current result. + + Hooked to _update_action_buttons rather than to + _recalc_beam_params because the latter fires only for fields in + CALC_BEAM_PARAMS_FIELDS -- editing a mechanism coefficient + changes eta substantially and would have left a stale value on + screen. Every site that assigns self.fit, including every one + that clears it, already calls _update_action_buttons, so this + cannot be bypassed by a path that forgets to call it.""" + fit = self.fit or {} + eta, gamma = fit.get("eta_peak"), fit.get("Gamma_peak") + self.calc_eta.set("--" if eta is None else f"{eta:.3f} rad") + self.calc_Gamma.set("--" if gamma is None else f"{gamma:.3f}") # ------------------------------------------------------------------ # Import @@ -1073,12 +1159,12 @@ class BDFresnelApp(tk.Tk): T=T, DeltaEoE=None, Delta_n=None) DeltaEoE = raw[:, col_DeltaEoE - 1] - lambda_ = self.params.lambda_ * 1e-9 + lambda_p = self.params.lambda_p * 1e-9 l = self.params.l * 1e-3 - w_0 = self.params.w_0 * 1e-6 - w_0_p = self.params.w_0p * 1e-6 - k_0 = 2 * np.pi / lambda_ - Delta_n = DeltaEoE / (k_0 * l * np.sqrt(2 / np.e) * (w_0 / w_0_p) * (2 / np.sqrt(np.pi))) + w_0_p = self.params.w_0_p * 1e-6 + w_0_e = self.params.w_0_e * 1e-6 + k_0 = 2 * np.pi / lambda_p + Delta_n = DeltaEoE / (k_0 * l * np.sqrt(2 / np.e) * (w_0_p / w_0_e) * (2 / np.sqrt(np.pi))) return dict( tau_d=tau_d, @@ -1147,8 +1233,8 @@ class BDFresnelApp(tk.Tk): # T_d_min/T_d_max are the values entered in the panel and are # left exactly as they are. if not simulating: - self.params.T_d_min = float(np.min(self.data["tau_d_shifted"])) / self.params.tau_p - self.params.T_d_max = float(np.max(self.data["tau_d_shifted"])) / self.params.tau_p + self.params.T_d_min = float(np.min(self.data["tau_d_shifted"])) / self.params.tau_e + self.params.T_d_max = float(np.max(self.data["tau_d_shifted"])) / self.params.tau_e # T_d_num is no longer forced here -- it is an input in the # Simulation Parameters box, defaulting to the 150 this line # used to hard-code. @@ -1159,7 +1245,7 @@ class BDFresnelApp(tk.Tk): def _fit_worker(self): t0 = time.time() try: - fit = BD_Fresnel_func_ni(self.params) + fit = BD_Fresnel_run(self.params) elapsed = time.time() - t0 self.after(0, self._on_fit_success, fit, elapsed) except Exception: @@ -1466,10 +1552,11 @@ class BDFresnelApp(tk.Tk): # and drawn by one method. PANELS = { "T": dict(key="T", color=TRANSMISSION_COLOR, ylabel="T (%)", - title="Transmission", range_key="T_points"), + title="Transmission", range_key="T_points", + y_sig_figs=3), "DeltaEoE": dict(key="DeltaEoE", color=DEFLECTION_COLOR, ylabel=r"$\Delta E/E$ (%)", title="Deflection", - range_key="DeltaEoE_points"), + range_key="DeltaEoE_points", y_sig_figs=None), } def _plot_signal_axis(self, ax, ctx, which, y_on_right=False): @@ -1481,6 +1568,8 @@ class BDFresnelApp(tk.Tk): the data's delay range and should be cut off at the border rather than overflow it. """ + from matplotlib.ticker import FuncFormatter + spec = self.PANELS[which] key, color = spec["key"], spec["color"] @@ -1510,6 +1599,25 @@ class BDFresnelApp(tk.Tk): ax.set_xlabel(rf"$\tau_d$ ({ctx['scale_label']})") ax.set_ylabel(spec["ylabel"]) ax.set_title(spec["title"]) # size from rc context + sig = spec.get("y_sig_figs") + if sig is not None: + # Transmission sits near 100%, so the default formatter + # spends most of its digits on the leading "99." and the + # labels get wide. "%.g" keeps the stated number of + # significant digits instead. + # + # The requested count is a floor, not a cap: a shallow scan + # spanning, say, 99.94 to 100% rounds every tick to "100" + # at three figures, leaving an unreadable axis. Digits are + # added only when that would happen, so an ordinary scan + # gets exactly the figures asked for. + ticks = [t for t in ax.get_yticks() + if min(ax.get_ylim()) <= t <= max(ax.get_ylim())] + while sig < 10 and len({f"{t:.{sig}g}" for t in ticks}) < len(ticks): + sig += 1 + ax.yaxis.set_major_formatter( + FuncFormatter(lambda value, _pos, n=sig: f"{value:.{n}g}")) + if y_on_right: ax.yaxis.tick_right() ax.yaxis.set_label_position("right") @@ -1614,10 +1722,10 @@ class BDFresnelApp(tk.Tk): # Axis labels as matplotlib mathtext, so Greek letters render as # Greek and sub/superscripts sit where they belong rather than - # showing the literal "tau_p" / "m^2" source. Figure *titles* keep + # showing the literal "tau_e" / "m^2" source. Figure *titles* keep # their plain-text form: they double as the Tk frame label and the # export filename, neither of which can render mathtext. - DIAG_LABEL_T = r"$t$ ($\tau_p$)" + DIAG_LABEL_T = r"$t$ ($\tau_e$)" DIAG_LABEL_R = r"$R[t]$ (m$^2$/W)" DIAG_LABEL_A = r"$A[t]$ (m/W)" DIAG_LABEL_DN = r"$\Delta n$ (unitless)" @@ -2035,68 +2143,69 @@ class BDFresnelApp(tk.Tk): lines.append(f"Import data file {p.import_filepath}.\n") lines.append(f"Operation mode: {MODE_LABELS[p.mode]}, " f"{RUN_MODE_LABELS[p.run_mode]}\n") + lines.append(f"Algorithm: {ALGO_LABELS[p.algorithm]}\n") if not simulating: lines.append("Data Columns:") - lines.append(f" tau_d column: {p.col_tau_d}") - lines.append(f" T column: {p.col_T}") + lines.append(f" tau_d column: {p.col_tau_d}") + lines.append(f" T column: {p.col_T}") if p.mode == MODE_PUMP_PROBE: lines.append(" DeltaEoE column: not used in Pump probe") else: - lines.append(f" DeltaEoE column: {p.col_DeltaEoE}") - lines.append(f" Delimiter: {describe_delimiter(p.delimiter)}\n") + lines.append(f" DeltaEoE column: {p.col_DeltaEoE}") + lines.append(f" Delimiter: {describe_delimiter(p.delimiter)}\n") # The delay grid is included so a run is reproducible from the # log alone: in Fitting mode T_d_min/T_d_max are derived from # the imported scan's delay range at fit time, in Simulation # mode they are entered directly. lines.append("Simulation Parameters:") - lines.append(f" X_num: {p.X_num}") - lines.append(f" X_max: {p.X_max} w_0") - lines.append(f" T_num: {p.T_num}") - lines.append(f" T_min: {p.T_min} tau_p") - lines.append(f" T_max: {p.T_max} tau_p") - lines.append(f" T_d_num: {p.T_d_num}") - lines.append(f" T_d_min: {p.T_d_min:.6g} tau_p") - lines.append(f" T_d_max: {p.T_d_max:.6g} tau_p\n") + lines.append(f" X_num: {p.X_num}") + lines.append(f" X_max: {p.X_max} w_0") + lines.append(f" T_num: {p.T_num}") + lines.append(f" T_min: {p.T_min} tau_e") + lines.append(f" T_max: {p.T_max} tau_e") + lines.append(f" T_d_num: {p.T_d_num}") + lines.append(f" T_d_min: {p.T_d_min:.6g} tau_e") + lines.append(f" T_d_max: {p.T_d_max:.6g} tau_e\n") lines.append("Pump (Excitation) Beam:") - lines.append(f" E_p: {p.E_p} uJ") - lines.append(f" tau_p_FWHM: {p.tau_p_FWHM} fs") - lines.append(f" tau_p (HW1/eM): {p.tau_p:6.3f} fs") - lines.append(f" w_0p: {p.w_0p} um") - lines.append(f" lambda_p: {p.lambda_p} nm\n") + lines.append(f" E_e: {p.E_e} uJ") + lines.append(f" tau_e_FWHM: {p.tau_e_FWHM} fs") + lines.append(f" tau_e (HW1/eM): {p.tau_e:6.3f} fs") + lines.append(f" w_0_e: {p.w_0_e} um") + lines.append(f" lambda_e: {p.lambda_e} nm\n") lines.append("Probe Beam:") - lines.append(f" tau_FWHM: {p.tau_FWHM} fs") - lines.append(f" tau (HW1/eM): {p.tau:6.3f} fs") - lines.append(f" w_0: {p.w_0} um") - lines.append(f" lambda: {p.lambda_} nm\n") + lines.append(f" tau_p_FWHM: {p.tau_p_FWHM} fs") + lines.append(f" tau_p (HW1/eM): {p.tau_p:6.3f} fs") + lines.append(f" w_0_p: {p.w_0_p} um") + lines.append(f" lambda_p: {p.lambda_p} nm\n") lines.append("Material @ Pump Wavelength:") - lines.append(f" R_p: {p.R_p * 100:6.3f} %") - lines.append(f" alpha_p: {p.alpha_p:6.3f} cm^-1") - lines.append(f" n_p: {p.n_p}") - lines.append(f" dndl_p: {p.dndl_p:6.6f} um^-1") - lines.append(f" alpha_2d: {p.alpha_2d} e-11 m/W\n") + lines.append(f" R_e: {p.R_e * 100:6.3f} %") + lines.append(f" alpha_e: {p.alpha_e:6.3f} cm^-1") + lines.append(f" n_e: {p.n_e}") + lines.append(f" dndl_e: {p.dndl_e:6.6f} um^-1") + lines.append(f" alpha_2d_e: {p.alpha_2d_e} e-11 m/W\n") lines.append("Material @ Probe Wavelength:") - lines.append(f" R: {p.R * 100:6.3f} %") - lines.append(f" alpha: {p.alpha:6.3f} cm^-1") - lines.append(f" n: {p.n}") - lines.append(f" dndl: {p.dndl:6.6f} um^-1\n") + lines.append(f" R_p: {p.R_p * 100:6.3f} %") + lines.append(f" alpha_p: {p.alpha_p:6.3f} cm^-1") + lines.append(f" n_p: {p.n_p}") + lines.append(f" dndl_p: {p.dndl_p:6.6f} um^-1\n") lines.append("System Geometry:") - lines.append(f" l: {p.l} mm") - lines.append(f" d: {p.d} cm") - lines.append(f" shift: {p.shift} fs") - lines.append(f" x_0: {p.x_0} w_0_p\n") + lines.append(f" l: {p.l} mm") + lines.append(f" d: {p.d} cm") + lines.append(f" shift: {p.shift} fs") + lines.append(f" x_0: {p.x_0} w_0_e\n") for i, mech in enumerate(p.mech): if mech.name == "None (both)": continue lines.append(f"Mechanism {i + 1}:") - lines.append(f" Type: {mech.name}") + lines.append(f" Type: {mech.name}") specs = MECHANISM_PARAM_SPECS.get(mech.name, []) for j, (pname, punits) in enumerate(specs): spacing = " " * max(1, 20 - len(pname)) @@ -2104,18 +2213,39 @@ class BDFresnelApp(tk.Tk): lines.append("") lines.append("Calculated Parameters (probe):") - lines.append(f" n_g: {p.ng:6.3f}") - lines.append(f" T_lin: {p.Tlin * 100:6.3f} %") - lines.append(f" z_0: {p.z_0 * 1e3:6.3f} mm\n") + lines.append(f" n_g_p: {p.ng_p:6.3f}") + lines.append(f" T_lin_p (transmission): {p.Tlin_p * 100:6.3f} %") + lines.append(f" z_0_p: {p.z_0_p * 1e3:6.3f} mm\n") + # Pump-side labels carry _e, matching their field names and the + # program-wide convention that the pump is subscripted and the + # probe is bare. The probe block above therefore stays n_g, + # T_lin, z_0. sigma_e sits next to T_lin_e because the two are + # the same statement: with no pump two-photon absorption + # T_lin_e = (1 - R_e) exp(-2 sigma_e). All five read from the + # parameters, not the result, so they report for either + # algorithm. lines.append("Calculated Parameters (pump):") - lines.append(f" n_g: {p.ng_p:6.3f}") - lines.append(f" T_lin: {p.Tlin_p * 100:6.3f} %") - lines.append(f" z_0: {p.z_0_p * 1e3:6.3f} mm") - lines.append(f" I_0: {p.I_0_p * 1e-13:6.3f} GW/cm^2\n") + lines.append(f" n_g_e: {p.ng_e:6.3f}") + lines.append(f" sigma_e: {p.sigma_e:6.3f}") + lines.append(f" T_lin_e (transmission): {p.Tlin_e * 100:6.3f} %") + lines.append(f" z_0_e: {p.z_0_e * 1e3:6.3f} mm") + lines.append(f" I_0_e: {p.I_0_e * 1e-13:6.3f} GW/cm^2\n") lines.append("Other:") - lines.append(f" rho: {p.rho:6.3f}\n") + lines.append(f" rho: {p.rho:6.3f}") + # Peak nonlinear phase and absorption exponent over the whole + # grid, from whichever algorithm produced the current result. + # eta_peak is the small-signal yardstick: the semi-analytical + # dP is first order in the response while Fresnel propagation + # keeps every order, so the two agree only while eta_peak stays + # small. Guarded because a result from an older session's saved + # state may predate these keys. + fit = self.fit or {} + if "eta_peak" in fit: + lines.append(f" eta (peak): {fit['eta_peak']:6.3f} rad") + lines.append(f" Gamma (peak): {fit['Gamma_peak']:6.3f}") + lines.append("") if exported_files: # Every file this export run produced. They all land in one @@ -2130,13 +2260,21 @@ class BDFresnelApp(tk.Tk): lines.append(f" {os.path.basename(path)}") lines.append("") lines.append("Please cite the following references when using products from this program.\n") - lines.append(' 1: Reichert, M., et al. (2014). "Temporal, spectral, and polarization ' - 'dependence of the nonlinear optical response of carbon disulfide." Optica 1(6): 436.\n') - lines.append(' 2: Reichert, M., et al. (2014). "Temporal, spectral, and polarization ' - 'dependence of the nonlinear optical response of carbon disulfide: supplementary ' - 'material." Optica 1(6): 436.\n') - lines.append(' 3: Ferdinandus, M. R., et al. (2013). "Beam deflection measurement of time ' - 'and polarization resolved ultrafast nonlinear refraction." Opt Lett 38(18): 3518-3521.\n') + # Optica style: every author, initials first, abbreviated + # journal, volume, page range, year. Wrapped with a hanging + # indent rather than run onto one very long line. + lines.append(' 1: M. Reichert, H. Hu, M. R. Ferdinandus, M. Seidel, P. Zhao, ' + 'T. R. Ensley,\n' + ' D. Peceli, J. M. Reed, D. A. Fishman, S. Webster, D. J. Hagan, and\n' + ' E. W. Van Stryland, \u201cTemporal, spectral, and polarization ' + 'dependence of\n' + ' the nonlinear optical response of carbon disulfide,\u201d ' + 'Optica 1, 436\u2013445 (2014).\n') + lines.append(' 2: M. R. Ferdinandus, H. Hu, M. Reichert, D. J. Hagan, and ' + 'E. W. Van Stryland,\n' + ' \u201cBeam deflection measurement of time and polarization resolved ' + 'ultrafast\n' + ' nonlinear refraction,\u201d Opt. Lett. 38, 3518\u20133521 (2013).\n') return "\n".join(lines) @@ -2146,7 +2284,12 @@ class BDFresnelApp(tk.Tk): # itself -- everything the export run produced. exported = [export_path, *image_paths, log_path] text = self._build_log_text(exported_files=exported) - with open(log_path, "w+", newline="\r\n") as f: + # encoding is explicit: the citation block uses typographic + # quotes and an en dash, and open() otherwise writes in the + # locale's encoding. Windows-1252 happens to contain those + # characters, but latin-1, cp437/cp850 and the CJK code pages + # do not, and would raise UnicodeEncodeError mid-export. + with open(log_path, "w+", newline="\r\n", encoding="utf-8") as f: f.write(text) # ------------------------------------------------------------------ diff --git a/last_settings.json b/last_settings.json new file mode 100644 index 0000000..50527a0 --- /dev/null +++ b/last_settings.json @@ -0,0 +1,165 @@ +{ + "E_e": 1.0, + "tau_e_FWHM": 45.0, + "w_0_e": 142.83, + "lambda_e": 800.0, + "tau_p_FWHM": 100.0, + "w_0_p": 22.253, + "lambda_p": 650.0, + "R_e": 0.0, + "alpha_e": 0.0, + "n_e": 1.4533, + "dndl_e": -0.017284, + "alpha_2d_e": 0.0, + "R_p": 0.0, + "alpha_p": 0.0, + "n_p": 1.4565, + "dndl_p": -0.027158, + "l": 1.72e-06, + "d": 15.0, + "shift": 70.0, + "x_0": 0.5, + "tau_e": 27.025254197695123, + "tau_p": 60.05612043932249, + "sigma_e": 0.0, + "I_0_e": 651473158047437.0, + "ng_e": 1.4671272, + "ng_p": 1.4741526999999999, + "rho": 0.8671350632529666, + "z_0_p": 0.0023933909907098232, + "z_0_e": 0.0801122184130848, + "Tlin_p": 1.0, + "Tlin_e": 1.0, + "X_max": 5.0, + "X_num": 50, + "T_min": -5.0, + "T_max": 5.0, + "T_num": 100, + "T_d_min": -9.579367435592124, + "T_d_max": 39.791355601447556, + "T_d_num": 150, + "n_mech": 7, + "mech": [ + { + "name": "Exponential rise/decay (both)", + "param": [ + 3600.0, + -200000.0, + 1.0, + 170.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Exponential rise/decay (both)", + "param": [ + 15000.0, + -500000.0, + 0.1, + 10000.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "None (both)", + "param": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "None (both)", + "param": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "None (both)", + "param": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "None (both)", + "param": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "None (both)", + "param": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "col_tau_d": 1, + "col_DeltaEoE": 2, + "col_T": 3, + "delimiter": ",", + "diagnostics": true, + "data_imported": true, + "data_fit": true, + "mode": "beam_deflection", + "run_mode": "fitting", + "algorithm": "semi_analytical", + "x_0_beam_deflection": 0.5, + "mech_beam_deflection": [], + "filename": "20190802 - BD 4 layer run 2_DeltaEoE_subtraction.txt", + "pathname": "/home/manuel/Documents/Projects/Code/BD_Fresnel_GUI/Test data/", + "import_filepath": "/home/manuel/Documents/Projects/Code/BD_Fresnel_GUI/Test data/20190802 - BD 4 layer run 2_DeltaEoE_subtraction.txt", + "settings_schema": 3 +} \ No newline at end of file