diff --git a/zscan_core.py b/zscan_core.py new file mode 100644 index 0000000..1109d26 --- /dev/null +++ b/zscan_core.py @@ -0,0 +1,1084 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +zscan_core.py +============= + +Simulation engine for the Z-scan open/closed aperture beam simulation, +refactored out of ZScan_beam_simulation_1_3_4.py so it can be driven by +a GUI (or a script, or a notebook) instead of hard-coded module-level +variables. Contains no GUI or pyplot state - figures are built with +matplotlib.figure.Figure so callers (e.g. a Tkinter FigureCanvasTkAgg) +can embed them directly. + +See ZScan_beam_simulation_1_3_4.py for the full derivation notes; the +physics and array shapes here are identical to that translation. +""" + +import os +import time +import datetime +import json +import colorsys +from dataclasses import dataclass, fields, asdict, replace + +import numpy as np +from scipy.interpolate import CubicSpline +from scipy.special import j0 +from scipy.optimize import minimize +import matplotlib as mpl +import matplotlib.colors as mcolors +from matplotlib.figure import Figure +from matplotlib.backends.backend_agg import FigureCanvasAgg + +# NumPy >= 2.0 renamed trapz() to trapezoid(); keep both names usable. +_trapz = getattr(np, "trapezoid", None) or np.trapz + + +def rmmissing(arr): + """Equivalent of MATLAB's rmmissing() for 1D arrays: drop NaNs.""" + return arr[~np.isnan(arr)] + + +# ============================================================================= +# CONFIGURATION +# ============================================================================= + +# Default size of the wings used for the slope-normalization fit, +# as a percentage of the scan's points taken from each end. +DEFAULT_ENDPTS_PERCENT = 10.0 + + +@dataclass +class ZScanConfig: + # --- file / column parameters --- + import_filepath: str = "" + delimiter: str = "" # "" -> auto (whitespace); e.g. "," or "\t" + extra_label: str = "" + z_col: int = 1 # 1-indexed, as in the original spreadsheet/MATLAB + CA_col: int = 2 + OA_col: int = 5 + REF_col: int = 8 + FREQ_col: int = 4 + + # --- processing flags --- + use_ref: bool = True + use_freq: bool = False + flip_z: int = 1 + do_norm_OA: bool = True + do_norm_CA: bool = True + flip_OA: int = 0 + flip_CA: int = 0 + flip_REF: int = 0 + flip_OA_disp: int = 0 + flip_CA_disp: int = 0 + show_CA: bool = True + + # --- nonlinear parameters --- + n_2: float = 10e-19 + n_3: float = 0e-33 + n_4: float = 0e-48 + alpha_2: float = 0 + alpha_3: float = 0e-28 + alpha_4: float = 2.2e-43 + + # --- z-position offsets [mm] --- + Delta_z_OA: float = 0.05 + Delta_z_CA: float = 0.23 + Delta_z_OACA: float = 0.0 + + # --- sample parameters --- + n: float = 3.0337 + L: float = 0.188e-3 + T_lin: float = 1.0 + + # --- laser parameters --- + E: float = 180e-9 + lambda_: float = 2000e-9 + w_0: float = 19e-6 + tau_FWHM: float = 50e-15 + M2: float = 1.0 + + # --- measurement parameters --- + S: float = 0.33 + d: float = 1.0 + + # --- error parameters (fractional, e.g. 0.10 = 10%) --- + E_err: float = 0.10 + w_err: float = 0.10 + tau_err: float = 0.10 + + # --- simulation grid --- + z_points: int = 76 # must be even + r_points: int = 500 + r_max: float = 3 + t_points: int = 50 + t_max: float = 3 + ra_points: int = 50 + endpts_percent: float = DEFAULT_ENDPTS_PERCENT # wing size for slope norm, % per side + max_iterations: int = 100 # Refine Fit's Nelder-Mead iteration cap + + +# ============================================================================= +# SETTINGS PERSISTENCE (save/load ZScanConfig as JSON) +# ============================================================================= + +def config_to_dict(cfg: ZScanConfig) -> dict: + return asdict(cfg) + + +def config_from_dict(d: dict) -> ZScanConfig: + """Builds a ZScanConfig from a dict, ignoring any keys that aren't + actual ZScanConfig fields (e.g. from an older/newer settings file) + so a partially-incompatible file doesn't crash the load -- missing + fields simply fall back to their dataclass defaults.""" + valid = {f.name for f in fields(ZScanConfig)} + return ZScanConfig(**{k: v for k, v in d.items() if k in valid}) + + +def save_settings(cfg: ZScanConfig, filepath: str) -> None: + with open(filepath, "w") as f: + json.dump(config_to_dict(cfg), f, indent=2) + + +def load_settings(filepath: str) -> ZScanConfig: + with open(filepath) as f: + d = json.load(f) + return config_from_dict(d) + + +# ============================================================================= +# DATA LOADING / PROCESSING +# ============================================================================= + +def peek_column_count(import_filepath: str, delimiter: str = "") -> int: + """ + Reads just enough of the data file to determine how many columns + it has, without fully processing it. Used by the GUI to constrain + which processing flags (use_ref/use_freq) are even selectable + before attempting a full load -- which could otherwise fail with + an out-of-bounds column index if those flags point past a smaller + file's actual column count. + """ + delim = delimiter if delimiter else None + V_DATA = np.genfromtxt(import_filepath, skip_header=1, delimiter=delim) + if V_DATA.ndim == 1: + return V_DATA.shape[0] + return V_DATA.shape[1] + + +def resolve_endpts(endpts_percent, n_pts) -> int: + """ + Turns cfg.endpts_percent into the concrete number of points taken + from each end of the scan for the wing (slope-normalization) fit: + floor(percent/100 * n_pts). At the 10% default this reproduces what + the count was hardcoded to before it became configurable. + + NOTE the two wings are not actually symmetric, despite the setting + being expressed per side: the leading wing is endpts points + (DATA[:endpts]) and the trailing wing is endpts + 1 + (DATA[-(endpts+1):]). That off-by-one is inherited from the MATLAB + original's 1:endpts vs end-endpts:end and is left as-is here so + fits stay reproducible against earlier results. build_log_text + reports both counts so what was actually used is never in doubt. + """ + if endpts_percent is None: + endpts_percent = DEFAULT_ENDPTS_PERCENT + + # Rounded down, but never below one point per side: a wing of zero + # leaves the line fit through a single point (polyfit warns and + # returns a meaningless slope). Reachable from a small percentage + # on a short scan, or from 0% -- which isn't rejected outright + # because the value is unused entirely when both do_norm flags + # are off. + endpts = max(int(np.floor(max(endpts_percent, 0.0) / 100.0 * n_pts)), 1) + + # The two wings together span 2*endpts + 1 points; beyond that they + # overlap in the middle and points get double-counted in the fit. + max_endpts = (n_pts - 1) // 2 + if endpts > max_endpts: + max_percent = np.floor(1000.0 * max_endpts / n_pts) / 10.0 + raise ValueError( + f"endpts = {endpts_percent:g}% of a {n_pts}-point scan is {endpts} points per " + f"side, so the leading ({endpts}) and trailing ({endpts + 1}) wings would " + f"overlap. Use {max_percent:g}% or less." + ) + return endpts + + +def load_and_normalize_data(cfg: ZScanConfig): + """ + Reads the raw z-scan data file, applies the frequency-channel + correction (if enabled), the reference-channel correction, + normalizes, and computes the linear-slope normalization lines. + Returns (DATA, norm_OA, norm_CA) where DATA is an (n, 11) array + whose columns match DATA(:,1..11) from the original MATLAB script + (here 0-indexed, so DATA[:, 0] == MATLAB DATA(:,1), etc.) + """ + z_col, CA_col, OA_col, REF_col, FREQ_col = ( + cfg.z_col - 1, cfg.CA_col - 1, cfg.OA_col - 1, cfg.REF_col - 1, cfg.FREQ_col - 1 + ) + + delim = cfg.delimiter if cfg.delimiter else None + V_DATA = np.genfromtxt(cfg.import_filepath, skip_header=1, delimiter=delim) + if V_DATA.ndim == 1: + V_DATA = V_DATA[None, :] + + Z_DATA = ((-1) ** cfg.flip_z) * V_DATA[:, z_col] + OA_DATA = 2 * np.median(V_DATA[:, OA_col]) * cfg.flip_OA + ((-1) ** cfg.flip_OA) * V_DATA[:, OA_col] + CA_DATA = 2 * np.median(V_DATA[:, CA_col]) * cfg.flip_CA + ((-1) ** cfg.flip_CA) * V_DATA[:, CA_col] + + if cfg.use_freq: + FREQ_DATA = V_DATA[:, FREQ_col] + FREQ_NORM = FREQ_DATA / np.mean(FREQ_DATA) + OA_DATA = OA_DATA / FREQ_NORM + CA_DATA = CA_DATA / FREQ_NORM + + if cfg.use_ref: + REF_DATA = 2 * np.median(V_DATA[:, REF_col]) * cfg.flip_REF + ((-1) ** cfg.flip_REF) * V_DATA[:, REF_col] + + rat = (OA_DATA / np.median(OA_DATA) - 1) / (REF_DATA / np.median(REF_DATA) - 1) + m_rat = np.median(rat) * ((-1) ** cfg.flip_REF) + REF_SCALED = (REF_DATA - np.median(REF_DATA)) * m_rat + np.median(REF_DATA) + REF_SCALED = REF_SCALED / np.median(REF_SCALED) + OA_DATA_CORR = OA_DATA / REF_SCALED + + rat = (CA_DATA / np.median(CA_DATA) - 1) / (REF_DATA / np.median(REF_DATA) - 1) + m_rat = np.median(rat) * ((-1) ** cfg.flip_REF) + REF_SCALED = (REF_DATA - np.median(REF_DATA)) * m_rat + np.median(REF_DATA) + REF_SCALED = REF_SCALED / np.median(REF_SCALED) + CA_DATA_CORR = CA_DATA / REF_SCALED + + else: + OA_DATA_CORR = OA_DATA + CA_DATA_CORR = CA_DATA + + n_pts = Z_DATA.shape[0] + DATA = np.zeros((n_pts, 11)) + DATA[:, 0] = Z_DATA - np.median(Z_DATA) + DATA[:, 1] = OA_DATA / np.median(OA_DATA) + DATA[:, 2] = OA_DATA_CORR / np.median(OA_DATA_CORR) + DATA[:, 3] = CA_DATA / np.median(CA_DATA) + DATA[:, 4] = CA_DATA_CORR / np.median(CA_DATA_CORR) + + endpts = resolve_endpts(cfg.endpts_percent, n_pts) + + if cfg.do_norm_OA: + OA_wings = np.vstack([DATA[:endpts, 0:3], DATA[-(endpts + 1):, 0:3]]) + OA_coeff = np.polyfit(OA_wings[:, 0], OA_wings[:, 2], 1) + norm_OA = np.polyval(OA_coeff, DATA[:, 0]) + else: + norm_OA = np.zeros(n_pts) + 1 + + if cfg.do_norm_CA: + CA_wings = np.vstack([DATA[:endpts, 0:5], DATA[-(endpts + 1):, 0:5]]) + CA_coeff = np.polyfit(CA_wings[:, 0], CA_wings[:, 4], 1) + norm_CA = np.polyval(CA_coeff, DATA[:, 0]) + else: + norm_CA = np.zeros(n_pts) + 1 + + DATA[:, 5] = DATA[:, 0] - cfg.Delta_z_OA + DATA[:, 6] = DATA[:, 2] / norm_OA + DATA[:, 7] = DATA[:, 0] - cfg.Delta_z_CA + DATA[:, 8] = DATA[:, 4] / norm_CA + DATA[:, 9] = DATA[:, 0] - cfg.Delta_z_OACA + DATA[:, 10] = DATA[:, 8] / DATA[:, 6] + + DATA[:, 6] = 2 * cfg.flip_OA_disp + ((-1) ** cfg.flip_OA_disp) * DATA[:, 6] + DATA[:, 8] = 2 * cfg.flip_CA_disp + ((-1) ** cfg.flip_CA_disp) * DATA[:, 8] + DATA[:, 10] = 2 * cfg.flip_CA_disp + ((-1) ** cfg.flip_CA_disp) * DATA[:, 10] + + return DATA, norm_OA, norm_CA + + +# ============================================================================= +# PHYSICS SIMULATION +# ============================================================================= + +def run_simulation(cfg: ZScanConfig, DATA: np.ndarray): + """ + Runs the full open/closed-aperture z-scan simulation for the given + config and (already-loaded/normalized) DATA array. Returns a dict + of results. + """ + t_start = time.time() + + if cfg.alpha_2 + cfg.alpha_3 + cfg.alpha_4 == 0: + alpha_2 = 1e-20 + else: + alpha_2 = cfg.alpha_2 + if cfg.n_2 + cfg.n_3 + cfg.n_4 == 0: + n_2 = 1e-50 + else: + n_2 = cfg.n_2 + n_3, n_4 = cfg.n_3, cfg.n_4 + alpha_3, alpha_4 = cfg.alpha_3, cfg.alpha_4 + + c = 299792458 + epsilon_0 = 8.854187817620e-12 + + tau = cfg.tau_FWHM / (2 * np.sqrt(np.log(2))) + k_0 = 2 * np.pi / cfg.lambda_ + + alpha = -np.log(cfg.T_lin) / cfg.L + kappa = alpha * cfg.lambda_ / (4 * np.pi) + Io = 2 * cfg.E / (np.pi ** 1.5 * cfg.w_0 ** 2 * tau) + + z_0 = np.pi * cfg.w_0 ** 2 / cfg.lambda_ + w_a = cfg.w_0 * (1 + cfg.M2 * (cfg.d / z_0) ** 2) ** 0.5 + r_a = w_a * np.sqrt(-0.5 * np.log(1 - cfg.S)) + # The simulated z range has to cover every data point on every + # offset axis, so it's padded by the largest offset in MAGNITUDE. + # Taking abs(max(...)) instead would pick the least-negative offset + # when all three are negative (e.g. -0.5, -0.3, -0.2 -> 0.2), too + # small a pad, pushing the outermost data points past the ends of + # the simulated curve and into extrapolation. + max_offset = max(abs(cfg.Delta_z_OA), abs(cfg.Delta_z_CA), abs(cfg.Delta_z_OACA)) + z_range = (np.max(np.abs(DATA[:, 0])) + max_offset) / (z_0 * 1e3) + + Tot_err = np.sqrt(cfg.E_err ** 2 + cfg.w_err ** 2 + cfg.tau_err ** 2) + + z_lin = np.linspace(-1, 1, cfg.z_points + 1) + z = np.sign(z_lin) * (z_lin ** 2) + z = z * z_range * z_0 + + w = cfg.w_0 * (1 + cfg.M2 * (z / z_0) ** 2) ** 0.5 + with np.errstate(divide='ignore', invalid='ignore'): + R = z + z_0 ** 2 / z + zeta = np.arctan(z / z_0) + + r_vec = np.linspace(0, cfg.r_max, cfg.r_points + 1) + r = np.outer(w, r_vec) + dr = r[:, 1] + + t = np.linspace(0, cfg.t_max * tau, cfg.t_points + 1) + dt = t[1] + + ra = np.linspace(0, r_a, cfg.ra_points + 1) + dra = ra[1] + + da = cfg.d - z + + # --- irradiance through sample --- + I_r = Io * (cfg.w_0 / w)[:, None] ** 2 * np.exp(-2 * (r / w[:, None]) ** 2) + Delta_n = n_2 * I_r + Ref = ((cfg.n + Delta_n - 1) ** 2 + kappa ** 2) / ((cfg.n + Delta_n + 1) ** 2 + kappa ** 2) + I_r1 = I_r * (1 - Ref) + I_t = np.exp(-(t / tau) ** 2) + I = I_r1[:, :, None] * I_t[None, None, :] + + if alpha == 0: + denom = alpha_2 + alpha_3 * I + alpha_4 * I ** 2 + I_exit = I / (1 + denom * cfg.L * I) + nl_phi = (k_0 * (n_2 + n_3 * I + n_4 * I ** 2) / denom + * np.log(1 + denom * cfg.L * I)) + else: + denom = alpha_2 + alpha_3 * I + alpha_4 * I ** 2 + I_exit = (alpha * I / ((alpha + denom * I) * np.exp(alpha * cfg.L) - denom * I)) + nl_phi = (k_0 * (n_2 + n_3 * I + n_4 * I ** 2) / denom + * (np.log((alpha + denom * I) * np.exp(alpha * cfg.L) - denom * I) + - alpha * cfg.L - np.log(alpha))) + + I = I_exit + + G_phase2d = 1j * k_0 * r ** 2 / (2 * R[:, None]) + 1j * zeta[:, None] + G_phase = G_phase2d[:, :, None] + + E_exit = (np.sqrt(2 / (c * epsilon_0) * I) * np.exp(1j * nl_phi) * np.exp(G_phase)) + + # --- propagate to closed aperture --- + # NOTE: this used to build E_EXIT * B as a full (Z, R, T, RA) array + # before summing over R via trapz -- at default grid sizes that + # intermediate is >1.5 GB and dominates both the memory and + # runtime of the whole simulation. It's mathematically just a + # trapezoidal-weighted contraction over the R axis for each Z, so + # it's computed here as a batched matrix multiply instead (same + # result to floating-point precision, ~250x faster on the default + # grid, and never materializes anything close to that size). + R_THING = r[:, :, None] # (Z, R, 1) + DA = da[:, None, None] # (Z, 1, 1) + RA = ra[None, None, :] # (1, 1, RA) + + with np.errstate(divide='ignore', invalid='ignore'): + A = (k_0 / (1j * DA)) * np.exp(1j * np.pi / (cfg.lambda_ * DA) * RA ** 2) # (Z, 1, RA) + B = (R_THING * np.exp(1j * np.pi / (cfg.lambda_ * DA) * R_THING ** 2) + * j0(k_0 * R_THING * RA / DA)) # (Z, R, RA) + + trapz_weight_r = np.ones(r.shape[1]) + trapz_weight_r[0] = 0.5 + trapz_weight_r[-1] = 0.5 + E_weighted = np.ascontiguousarray((E_exit * trapz_weight_r[None, :, None]).transpose(0, 2, 1)) # (Z, T, R) + integral_r = np.matmul(E_weighted, B) # batched (T,R)@(R,RA) per Z -> (Z, T, RA) + + E_ap = integral_r * A * dr[:, None, None] # (Z, T, RA) + + # --- OA / CA signals --- + integral_t_OA = _trapz(I, axis=2) + weighted_OA = integral_t_OA * (2 * dt) * r + integral_r_OA = _trapz(weighted_OA, axis=1) + OA = integral_r_OA * (2 * np.pi * dr) + OA = OA / OA[0] + + integral_t_CA = _trapz(np.abs(E_ap) ** 2, axis=1) + weighted_CA = integral_t_CA * (2 * dt) * ra[None, :] + integral_ra_CA = _trapz(weighted_CA, axis=1) + CA = (c * epsilon_0 / 2) * integral_ra_CA * (2 * np.pi * dra) + CA = CA / ((CA[0] + CA[-1]) / 2) + + CAOA = CA / OA + + # --- goodness of fit --- + # Each fit curve is interpolated onto its own offset z-axis + # (columns 5 / 7 / 9) and must therefore be compared against the + # matching *processed* data series on that same axis: column 6 + # (referenced + slope-normalized OA), column 8 (referenced + + # slope-normalized CA) and column 10 (CA/OA). Columns 1 / 2 / 3 + # are intermediate raw/referenced values on the un-offset axis and + # are only kept for the Referenced/Normalized plot. These are the + # same series plotted by make_fit_figure and used by _fit_rmse. + # + # All three are resampled the same way, with a cubic spline through + # the simulated points. np.interp (piecewise linear) was used for + # CA/CAOA, which on a ~77-point simulation grid visibly flattens + # the CA peak and valley -- the two features the whole measurement + # is about -- and biased CA_chi_square accordingly. It also + # disagreed with OA at the edges: np.interp clamps to the end + # values outside the grid, CubicSpline extrapolates. With z_range + # padded by the largest offset magnitude, the data should sit + # inside the simulated range anyway. + z_mm = z * 1e3 + OA_interp = CubicSpline(z_mm, OA)(DATA[:, 5]) + OA_chi_square = np.sum(rmmissing(((OA_interp - DATA[:, 6]) ** 2) / OA_interp)) + + CA_interp = CubicSpline(z_mm, CA)(DATA[:, 7]) + CA_chi_square = np.sum(rmmissing(((CA_interp - DATA[:, 8]) ** 2) / CA_interp)) + + CAOA_interp = CubicSpline(z_mm, CAOA)(DATA[:, 9]) + CAOA_chi_square = np.sum(rmmissing(((CAOA_interp - DATA[:, 10]) ** 2) / CAOA_interp)) + + deltaOAcomp = np.array([1 - np.min(DATA[:, 6]), 1 - np.min(OA_interp)]) + deltaCAcomp = np.array([np.max(DATA[:, 8]) - np.min(DATA[:, 8]), + np.max(CA_interp) - np.min(CA_interp)]) + deltaCAOAcomp = np.array([np.max(DATA[:, 10]) - np.min(DATA[:, 10]), + np.max(CAOA_interp) - np.min(CAOA_interp)]) + + elapsed = time.time() - t_start + + return dict( + z=z, z_mm=z_mm, OA=OA, CA=CA, CAOA=CAOA, + OA_interp=OA_interp, CA_interp=CA_interp, CAOA_interp=CAOA_interp, + OA_chi_square=OA_chi_square, CA_chi_square=CA_chi_square, CAOA_chi_square=CAOA_chi_square, + deltaOAcomp=deltaOAcomp, deltaCAcomp=deltaCAcomp, deltaCAOAcomp=deltaCAOAcomp, + Io=Io, z_0=z_0, tau=tau, kappa=kappa, Tot_err=Tot_err, z_range=z_range, + elapsed=elapsed, + ) + + +# ============================================================================= +# AUTOMATIC FIT REFINEMENT (downhill simplex / Nelder-Mead) +# ============================================================================= + +# Characteristic scale for each nonlinear parameter, in SI units -- +# chosen to match each parameter's own typical/default magnitude (not +# the *display* unit conversion factors used in the log, which don't +# normalize to an O(1) value -- e.g. n_2's default of 1e-18 shown as +# "1.000e-05 cm^2/GW" is a display-readability choice, not a hint that +# 1e13 is n_2's natural scale). Nelder-Mead isn't scale-invariant, and +# these parameters span ~30 orders of magnitude from each other (n_2 +# ~1e-18, alpha_4 ~1e-43), so the optimizer runs in normalized +# coordinates (actual_value / scale) where every parameter starts +# close to O(1), rather than in raw SI units where it would fail +# outright. +NONLINEAR_PARAM_SCALES = { + "n_2": 1e-18, "n_3": 1e-33, "n_4": 1e-48, + "alpha_2": 1e-13, "alpha_3": 1e-28, "alpha_4": 1e-43, +} + + +def _fit_rmse(cfg: ZScanConfig, DATA, results) -> float: + """RMSE between the simulated fit curves and the actual data, + using exactly the same "Fit" vs "Data" series shown in the Fit + Results tab (OA + CA, or OA + CAOA when show_CA is off).""" + resid_OA = results['OA_interp'] - DATA[:, 6] + if cfg.show_CA: + resid_2 = results['CA_interp'] - DATA[:, 8] + else: + resid_2 = results['CAOA_interp'] - DATA[:, 10] + resid = np.concatenate([resid_OA, resid_2]) + return float(np.sqrt(np.mean(resid ** 2))) + + +def refine_fit(cfg: ZScanConfig, DATA, param_names, max_iter=200, progress_callback=None): + """ + Uses a downhill simplex (Nelder-Mead) search over the given subset + of nonlinear parameters (any of "n_2", "n_3", "n_4", "alpha_2", + "alpha_3", "alpha_4") to minimize the RMSE between the simulated + fit and the actual data (see _fit_rmse). Every other field of cfg, + including any nonlinear parameter NOT in param_names, is held + fixed at its current value. + + progress_callback(iteration, rmse), if given, is called after + every trial simulation -- useful for a GUI to show live progress, + since each iteration can take a fraction of a second to a few + seconds depending on grid size. + + Returns (best_cfg, best_results, opt_result) where opt_result is + scipy's raw OptimizeResult (opt_result.nit, .nfev, .success, etc.) + """ + if not param_names: + raise ValueError("No parameters selected for fitting -- check at least one " + "checkbox in Nonlinear Parameters first.") + unknown = [p for p in param_names if p not in NONLINEAR_PARAM_SCALES] + if unknown: + raise ValueError(f"Not a nonlinear fit parameter: {unknown}") + + scales = np.array([NONLINEAR_PARAM_SCALES[p] for p in param_names]) + x0 = np.array([getattr(cfg, p) for p in param_names], dtype=float) / scales + + # Explicit initial simplex, one fixed-size step (in normalized + # coordinates, where a "reasonable" value is O(1)) per dimension + # from x0. scipy's own default initial-simplex construction uses + # a *relative* perturbation, which collapses to a tiny step for + # any parameter starting at exactly 0 (a common case here, since + # several nonlinear parameters default to 0) -- that tiny step + # can leave Nelder-Mead unable to explore that dimension enough to + # converge within a practical iteration budget. A fixed absolute + # step sidesteps that regardless of each parameter's starting value. + n_params = len(x0) + initial_simplex = np.tile(x0, (n_params + 1, 1)) + for i in range(n_params): + initial_simplex[i + 1, i] += 0.5 + + iteration = [0] + + def objective(x_norm): + trial_kwargs = {p: x_norm[i] * scales[i] for i, p in enumerate(param_names)} + trial_cfg = replace(cfg, **trial_kwargs) + try: + results = run_simulation(trial_cfg, DATA) + rmse = _fit_rmse(trial_cfg, DATA, results) + except Exception: + rmse = np.inf + if not np.isfinite(rmse): + rmse = 1e30 + iteration[0] += 1 + if progress_callback is not None: + progress_callback(iteration[0], rmse) + return rmse + + opt_result = minimize( + objective, x0, method='Nelder-Mead', + options=dict(maxiter=max_iter, xatol=1e-8, fatol=1e-12, adaptive=True, + initial_simplex=initial_simplex), + ) + + best_kwargs = {p: opt_result.x[i] * scales[i] for i, p in enumerate(param_names)} + best_cfg = replace(cfg, **best_kwargs) + best_results = run_simulation(best_cfg, DATA) + return best_cfg, best_results, opt_result + + +# ============================================================================= +# FIGURES (matplotlib.figure.Figure - embeddable, no pyplot state) +# ============================================================================= + +# Padding for tight_layout, in multiples of the font size (10pt), so +# 0.3 -> 0.042in and 0.5 -> 0.069in. pad is the margin around the +# OUTSIDE of the figure and w_pad the gap BETWEEN the two panels. +# Matplotlib defaults both to 0.8, which spends 0.111in on each of the +# four outer edges -- more than the figure needs, since the outermost +# artists are already tight-measured -- while the gap between the +# panels is a deliberate, separately chosen amount. +LAYOUT_PAD = 0.3 +LAYOUT_W_PAD = 0.5 + +# Below this much clear space between the innermost tick labels, the +# closed-aperture panel's leading one is dropped. w_pad is what sets +# that space, so the check below is against w_pad directly. +JUNCTION_MIN_LABEL_GAP_PT = 3.0 + +# set_box_aspect fixes each panel's height/width ratio, so whenever the +# slot tight_layout allocates is wider than that ratio allows, the axes +# shrinks inside its slot. By default it then centres, putting half the +# leftover on each side -- which drops slack right at the join between +# the two panels, on top of anything w_pad contributes. Anchoring the +# left panel West and the right panel East pushes both toward the +# figure's outer edges instead, so anything left over collects between +# the panels rather than as blank margin down the sides of the image. +# At the padding above these figures lay out with no leftover at all +# and the anchors make no difference; they matter only if the content +# changes enough to reintroduce it (longer tick labels, a bigger font), +# and then this is the side to err on. +PANEL_ANCHOR_LEFT = "W" +PANEL_ANCHOR_RIGHT = "E" + +def _renderer_for(fig): + """A renderer for measuring text, reusing the figure's own canvas + when it has one. Only falls back to attaching a fresh Agg canvas + when the figure has none yet -- important because rebinding + fig.canvas out from under an embedded FigureCanvasTkAgg would + detach the figure from the widget drawing it.""" + canvas = fig.canvas + if canvas is None or not hasattr(canvas, "get_renderer"): + canvas = FigureCanvasAgg(fig) + return canvas.get_renderer() + + +def _x_tick_label_artists(ax): + """Every x tick label Text on ax, INCLUDING ones currently hidden. + ax.get_xticklabels() silently drops invisible labels, so using it + here would make hiding a label irreversible -- the restore pass + below could never see it again to turn it back on.""" + return [tick.label1 for tick in ax.xaxis.get_major_ticks()] + + +def _x_tick_labels_inside(ax, renderer): + """(label, bbox) for the x tick labels actually drawn inside ax. + Matplotlib keeps tick objects for positions beyond the view limits, + and their bboxes land outside the axes entirely, so they have to be + filtered out or they're mistaken for the innermost label.""" + axes_box = ax.get_window_extent() + found = [] + for label in _x_tick_label_artists(ax): + if not label.get_text() or not label.get_visible(): + continue + bb = label.get_window_extent(renderer) + if bb.width <= 0: + continue + centre = 0.5 * (bb.x0 + bb.x1) + if axes_box.x0 - 1 <= centre <= axes_box.x1 + 1: + found.append((label, bb)) + return found + + +def _junction_labels_crowded(fig): + """Whether the innermost x tick labels of the two panels will run + together at the join. + + Tested by asking, of each panel separately, whether its innermost + tick label overhangs its own spine -- which happens when a tick + lands within half a label width of that axes' data limit. If both + do, the labels must touch: w_pad is zero, so tight_layout brings the + two TIGHT bboxes (labels included) flush, leaving the overhanging + labels adjacent no matter how wide the figure is. + + Deliberately not measured as "how many pixels apart are the two + labels right now", which sounds more direct but is path-dependent: + tight_layout is not idempotent -- it derives new subplot params from + bboxes that depend on the current ones -- so the same figure laid + out twice gives slightly different spacing, and a fixed pixel + threshold flip-flops across repeated re-layouts. An overhang is a + property of the tick position and the font, so it gives the same + answer at any figure size and on any call. + """ + # w_pad is exactly the clear space tight_layout leaves between the + # two tight bboxes, so when it is wide enough on its own the labels + # cannot run together and nothing needs measuring. + if LAYOUT_W_PAD * mpl.rcParams["font.size"] >= JUNCTION_MIN_LABEL_GAP_PT: + return False + + left_ax, right_ax = sorted(fig.axes, key=lambda ax: ax.get_position().x0) + renderer = _renderer_for(fig) + + # Tick positions have to be refreshed before they can be measured: + # tight_layout has just moved the axes, and the tick Texts still + # carry the positions (and, if the locator picked a different set at + # the new width, the texts) from before the move. Only the Axis is + # asked for its tight bbox, not the whole Axes -- that updates the + # ticks just the same, but walks two axis artists instead of every + # line and marker in the plot. A canvas.draw() or a full + # Axes.get_tightbbox() here each cost ~30ms per call, which a + # window-resize drag fires continuously; this costs ~2ms. + for ax in (left_ax, right_ax): + ax.xaxis.get_tightbbox(renderer) + + left = _x_tick_labels_inside(left_ax, renderer) + right = _x_tick_labels_inside(right_ax, renderer) + if not left or not right: + return False + + overhangs_right = max(bb.x1 for _, bb in left) > left_ax.get_window_extent().x1 + overhangs_left = min(bb.x0 for _, bb in right) < right_ax.get_window_extent().x0 + return overhangs_right and overhangs_left + + +def apply_tight_layout(fig): + """The single tight_layout() call used everywhere these figures are + laid out -- at creation, on every GUI resize, and before export -- + so the settings can't drift apart between call sites. + + w_pad is the padding BETWEEN the two subplots, and it's zero, so + they sit flush. Matplotlib's default is w_pad = pad = 0.8 font-size + units, 0.111in of blank space down the middle at 10pt; that default + is there to keep one subplot's right-hand tick labels off its + neighbour, but these figures put ax1's y-axis on the far left and + ax2's on the far right, so nothing is drawn in it. pad, the padding + around the OUTSIDE of the figure, is unchanged. + + The one thing that does reach the join is the innermost pair of x + tick labels. In the reference figure, whose data runs to exactly + +/-4mm, ticks land on both axes' edges and meet as "4-4", reading as + a single number; when _junction_labels_crowded sees that, the + closed-aperture plot's leading label is dropped and the figure laid + out again to take up the freed space. + + Each call restores every label and lays out from that clean state + BEFORE measuring, so the decision always reflects what the figure + would look like untouched. Deciding from whatever the previous call + left behind instead makes this unstable: the second call measures a + layout that was computed for a hidden label, sees a comfortable gap, + and puts the label back -- so re-laying out the same figure twice + flip-flops rather than settling. + """ + two_panel = len(fig.axes) == 2 + if two_panel: + for ax in fig.axes: + for label in _x_tick_label_artists(ax): + label.set_visible(True) + + fig.tight_layout(pad=LAYOUT_PAD, w_pad=LAYOUT_W_PAD) + + if two_panel and _junction_labels_crowded(fig): + right_ax = max(fig.axes, key=lambda ax: ax.get_position().x0) + renderer = _renderer_for(fig) + inside = _x_tick_labels_inside(right_ax, renderer) + if inside: + min(inside, key=lambda pair: pair[1].x0)[0].set_visible(False) + fig.tight_layout(pad=LAYOUT_PAD, w_pad=LAYOUT_W_PAD) + return fig + + +def _apply_plot_fonts(ax, title_size=8, label_size=7, tick_size=7, legend_size=6): + """Standard font sizes used across every Z-scan plot: 7pt tick + labels and axis labels, 8pt titles, 6pt legend text. Font family + is left at Matplotlib's default (rcParams['font.family']).""" + ax.title.set_fontsize(title_size) + ax.xaxis.label.set_fontsize(label_size) + ax.yaxis.label.set_fontsize(label_size) + ax.tick_params(axis='both', labelsize=tick_size) + leg = ax.get_legend() + if leg is not None: + for text in leg.get_texts(): + text.set_fontsize(legend_size) + + +def _trim_vertical_whitespace(fig, margin_in=0.1): + """Shrinks the figure's height to match its actual rendered + content (plus a small margin), removing the excess top/bottom + whitespace that's left over because the fixed-aspect-ratio axes + (set_box_aspect) don't necessarily fill the figure's full height. + Uses a temporary Agg canvas purely to measure the tight bounding + box; the figure can still be freely re-attached to a different + canvas afterward (e.g. FigureCanvasTkAgg when embedded in the + GUI), same as savefig() does internally. + """ + canvas = FigureCanvasAgg(fig) + canvas.draw() + bbox = fig.get_tightbbox(canvas.get_renderer()) + new_height = bbox.height + margin_in + if new_height < fig.get_figheight(): + fig.set_figheight(new_height) + apply_tight_layout(fig) + return fig + + +def _resize_for_export(fig, target_width_in=6.5): + """Resizes fig to be target_width_in inches wide, preserving its + current aspect ratio (width/height) exactly, and refreshes the + layout for the new size. Figures embedded in the GUI can have been + resized to fit the window before export is triggered, so this is + applied fresh right before every savefig() call rather than relying + on the figure's size at creation time. + """ + aspect = fig.get_figwidth() / fig.get_figheight() + fig.set_size_inches(target_width_in, target_width_in / aspect) + apply_tight_layout(fig) + return fig + + +def _marker_size_for_data(n_pts): + """Data-point marker size scales down as more points are plotted, + to reduce visual clutter: more than 150 points -> size 2, 100-149 + points -> size 3, fewer than 100 points -> size 4.""" + if n_pts > 150: + return 2 + elif n_pts >= 100: + return 3 + else: + return 4 + + +def _desaturate(color, saturation=0.5): + """Returns `color` at the given HSV saturation (0-1), preserving + its hue and value -- e.g. red at 50% saturation is a lighter, + pastel red rather than the fully-saturated original.""" + r, g, b = mcolors.to_rgb(color) + h, _, v = colorsys.rgb_to_hsv(r, g, b) + return colorsys.hsv_to_rgb(h, saturation, v) + + +PANEL_BOX_ASPECT = 0.8 +LEGEND_KWARGS = dict(labelspacing=0.2, borderpad=0.2, handlelength=1.2, + handletextpad=0.4, borderaxespad=0.3) + + +def _style_panel(ax, title, right_hand=False, legend_handles=None, legend_labels=None): + """Everything the two panels of both figures have in common: title, + axis labels, tight autoscale, fixed box aspect, anchor, legend and + fonts. The right-hand panel additionally moves its y-axis to the + outside of the figure. + + _apply_plot_fonts has to come after the legend exists, since it + sizes the legend text too. + """ + if right_hand: + ax.yaxis.set_label_position('right') + ax.yaxis.tick_right() + ax.set_title(title) + ax.set_xlabel('z (mm)') + ax.set_ylabel('T (normalized)') + ax.autoscale(enable=True, tight=True) + ax.set_box_aspect(PANEL_BOX_ASPECT) + ax.set_anchor(PANEL_ANCHOR_RIGHT if right_hand else PANEL_ANCHOR_LEFT) + if legend_handles is None: + ax.legend(**LEGEND_KWARGS) + else: + ax.legend(legend_handles, legend_labels, **LEGEND_KWARGS) + _apply_plot_fonts(ax) + + +def _finish_figure(fig): + """Lay out, then shrink the figure to the height its content + actually needs. Both figures end this way.""" + apply_tight_layout(fig) + _trim_vertical_whitespace(fig) + return fig + + +def make_reference_figure(DATA, norm_OA, norm_CA, do_norm_OA=True, do_norm_CA=True, line_width=1.25): + fig = Figure(figsize=(9, 4.2)) + ax1, ax2 = fig.subplots(1, 2) + + ax1.plot(DATA[:, 0], DATA[:, 1], '-', color=_desaturate('r'), linewidth=line_width, label='Raw') + ax1.plot(DATA[:, 0], DATA[:, 2], '-', color='r', linewidth=line_width, label="Ref'd") + if do_norm_OA: + ax1.plot(DATA[:, 0], norm_OA, 'k:', linewidth=line_width, label='Norm') + _style_panel(ax1, 'Open aperture') + + ax2.plot(DATA[:, 0], DATA[:, 3], '-', color=_desaturate('b'), linewidth=line_width, label='Raw') + ax2.plot(DATA[:, 0], DATA[:, 4], '-', color='b', linewidth=line_width, label="Ref'd") + if do_norm_CA: + ax2.plot(DATA[:, 0], norm_CA, 'k:', linewidth=line_width, label='Norm') + _style_panel(ax2, 'Closed aperture', right_hand=True) + + return _finish_figure(fig) + + +def make_fit_figure(cfg: ZScanConfig, DATA, results, line_width=1.25): + fig = Figure(figsize=(9, 4.2)) + ax1, ax2 = fig.subplots(1, 2) + marker_size = _marker_size_for_data(DATA.shape[0]) + + fit_line, = ax1.plot(DATA[:, 5], results['OA_interp'], '-r', linewidth=line_width, label='Fit') + data_line, = ax1.plot(DATA[:, 5], DATA[:, 6], 'o', markerfacecolor='none', markeredgecolor='r', + markersize=marker_size, markeredgewidth=0.5, label='Data') + _style_panel(ax1, 'Open aperture', + legend_handles=[data_line, fit_line], legend_labels=['Data', 'Fit']) + + if cfg.show_CA: + fit_line2, = ax2.plot(DATA[:, 7], results['CA_interp'], '-b', linewidth=line_width, label='Fit') + data_line2, = ax2.plot(DATA[:, 7], DATA[:, 8], 'o', markerfacecolor='none', markeredgecolor='b', + markersize=marker_size, markeredgewidth=0.5, label='Data') + title2 = 'Closed aperture' + else: + fit_line2, = ax2.plot(DATA[:, 9], results['CAOA_interp'], '-b', linewidth=line_width, label='Fit') + data_line2, = ax2.plot(DATA[:, 9], DATA[:, 10], 'o', markerfacecolor='none', markeredgecolor='b', + markersize=marker_size, markeredgewidth=0.5, label='Data') + title2 = 'Closed over open aperture (data / fit)' + _style_panel(ax2, title2, right_hand=True, + legend_handles=[data_line2, fit_line2], legend_labels=['Data', 'Fit']) + + return _finish_figure(fig) + + +# ============================================================================= +# EXPORT +# ============================================================================= + +def _save_at_export_size(fig, jpg_path, svg_path): + """Saves fig as JPG + SVG at the standard export size, then puts it + back to the size it had on entry. Without the restore, exporting + from the GUI leaves the *live, embedded* figure resized to the + export width: the on-screen plot stays wrong until the user happens + to resize the window and ResizableFigureCanvas recomputes it. + """ + original_size = fig.get_size_inches().copy() + try: + _resize_for_export(fig) + fig.savefig(jpg_path, format='jpg', dpi=300) + fig.savefig(svg_path, format='svg') + finally: + fig.set_size_inches(original_size) + apply_tight_layout(fig) + + +def build_log_text(cfg: ZScanConfig, DATA, results, exported_paths=None) -> str: + """ + Builds the full Z-scan fit report as a string -- used both to + write the _log.txt file on export and to populate the GUI's + "Fit Quality / Log" tab immediately after a run completes (before + any export has happened yet -- pass exported_paths=None for that + case, which omits the "Exported files:" listing). When exporting, + pass the complete list of file paths being written (CSV, the log + file itself, JPG/SVG images, etc.) so the log lists everything + that was exported alongside it. + """ + lines = [] + lines.append(f"{datetime.datetime.now()}: Begin Z-scan program (zscan_gui.py / zscan_core.py).") + lines.append(f"Import data file {cfg.import_filepath}.\n") + + lines.append('Data Columns (1-indexed):') + lines.append(f' z column: {cfg.z_col}') + lines.append(f' CA column: {cfg.CA_col}') + lines.append(f' OA column: {cfg.OA_col}') + lines.append(f' REF column: {cfg.REF_col}') + lines.append(f' FREQ column: {cfg.FREQ_col}\n') + + lines.append('Data Offsets:') + lines.append(f' Delta_z_OA: {cfg.Delta_z_OA:6.3f} mm') + lines.append(f' Delta_z_CA: {cfg.Delta_z_CA:6.3f} mm\n') + + lines.append('Simulation Parameters:') + lines.append(f' z_points: {cfg.z_points}') + lines.append(f" z_range: {2 * results['z_range']:6.3f} z_0") + lines.append(f' r_points: {cfg.r_points}') + lines.append(f' r_max: {cfg.r_max:6.3f} w_0') + lines.append(f' t_points: {cfg.t_points}') + lines.append(f' t_max: {cfg.t_max:6.3f} tau') + lines.append(f' ra_points: {cfg.ra_points}') + resolved_endpts = resolve_endpts(cfg.endpts_percent, DATA.shape[0]) + lines.append(f' endpts: {cfg.endpts_percent:6.3f} % per side ' + f'({resolved_endpts} leading / {resolved_endpts + 1} trailing points)') + lines.append(f' max_iterations: {cfg.max_iterations}\n') + + lines.append('Processing Parameters:') + lines.append(f' use_ref: {bool(cfg.use_ref)}') + lines.append(f' use_freq: {bool(cfg.use_freq)}') + lines.append(f' flip_z: {bool(cfg.flip_z)}') + lines.append(f' do_norm_OA: {bool(cfg.do_norm_OA)}') + lines.append(f' do_norm_CA: {bool(cfg.do_norm_CA)}') + lines.append(f' flip_OA: {bool(cfg.flip_OA)}') + lines.append(f' flip_CA: {bool(cfg.flip_CA)}') + lines.append(f' flip_REF: {bool(cfg.flip_REF)}') + lines.append(f' flip_OA_disp: {bool(cfg.flip_OA_disp)}') + lines.append(f' flip_CA_disp: {bool(cfg.flip_CA_disp)}\n') + + lines.append('Fit Parameters:') + lines.append(f' n_2: {cfg.n_2 * 1e13:.5e} cm^2/GW') + lines.append(f' n_3: {cfg.n_3 * 1e26:.5e} cm^4/GW^2') + lines.append(f' n_4: {cfg.n_4 * 1e39:.5e} cm^6/GW^3\n') + + lines.append(f' alpha_2: {cfg.alpha_2 * 1e11:.5e} cm/GW') + lines.append(f' alpha_3: {cfg.alpha_3 * 1e24:.5e} cm^3/GW^2') + lines.append(f' alpha_4: {cfg.alpha_4 * 1e37:.5e} cm^5/GW^3\n') + + lines.append(f' E: {cfg.E * 1e9:6.3f} nJ') + lines.append(f" I_0: {results['Io'] * 1e-13:6.3f} GW/cm^2") + lines.append(f' lambda: {cfg.lambda_ * 1e9:6.3f} nm') + lines.append(f' w_0 (HW1/e^2M): {cfg.w_0 * 1e6:6.3f} um') + lines.append(f" z_0: {results['z_0'] * 1e3:6.3f} mm") + lines.append(f' tau (FWHM): {cfg.tau_FWHM * 1e15:6.3f} fs') + lines.append(f" tau (HW1/eM): {results['tau'] * 1e15:6.3f} fs") + lines.append(f' M^2: {cfg.M2:6.3f}\n') + + lines.append(f' n: {cfg.n:6.3f}') + lines.append(f' L: {cfg.L * 1e3:6.3f} mm') + lines.append(f' T_lin: {cfg.T_lin:6.3f}') + lines.append(f" kappa: {results['kappa']:6.3f}\n") + + lines.append(f' S: {cfg.S:6.3f}') + lines.append(f' d: {cfg.d * 1e3:6.3f} mm\n') + + lines.append('DeltaT_PV comparison:') + lines.append(f" Delta_OA_comp: {np.round(results['deltaOAcomp'], 3)} (data / fit)") + lines.append(f" Delta_CA_comp: {np.round(results['deltaCAcomp'], 3)} (data / fit)") + lines.append(f" Delta_CAOA_comp: {np.round(results['deltaCAOAcomp'], 3)} (data / fit)\n") + + lines.append('Fit Quality:') + lines.append(f" OA_chi^2: {results['OA_chi_square']:6.3f}") + lines.append(f" CA_chi_2: {results['CA_chi_square']:6.3f}") + lines.append(f" CAOA_chi_2: {results['CAOA_chi_square']:6.3f}\n") + + lines.append('Error estimates:') + lines.append(f' E_err: {cfg.E_err * 100:6.3f} %') + lines.append(f' w_err: {cfg.w_err * 100:6.3f} %') + lines.append(f' tau_err: {cfg.tau_err * 100:6.3f} %') + lines.append(f" Tot_err: {results['Tot_err'] * 100:6.2f} %\n") + + if exported_paths: + lines.append('Exported files:') + for p in exported_paths: + lines.append(f' {p}') + lines.append('') + lines.append(f"Elapsed time is {results['elapsed']:6.2f} seconds.\n") + + return "\n".join(lines) + + +def export_results(cfg: ZScanConfig, DATA, results, fit_fig, ref_fig=None): + """ + Writes the fit/data CSV, a full log file (via build_log_text, which + lists every exported file), a JPG + SVG snapshot of fit_fig, and + (if provided) a JPG + SVG snapshot of ref_fig (the "Referenced / + Normalized" figure). + """ + # Derived from the filename stem rather than by replacing the + # literal substring '.txt' in the full path. That replacement was + # wrong in two ways: for an input that isn't named .txt (the file + # dialog also offers .dat and .csv) nothing matched, so every + # output path came out equal to the INPUT path and the first write + # overwrote the user's raw data; and for any path with '.txt' + # elsewhere in it (a directory named "2019.txt data", say) it + # substituted there too and wrote somewhere unintended. + root, ext = os.path.splitext(cfg.import_filepath) + stem = root + cfg.extra_label + '_fit' + export_filepath = stem + (ext if ext else '.txt') + logfile_exportpath = stem + '_log.txt' + picture_path = stem + '.jpg' + svg_path = stem + '.svg' + + if os.path.abspath(export_filepath) == os.path.abspath(cfg.import_filepath): + raise ValueError( + f"Export would overwrite the input data file ({cfg.import_filepath}). " + f"Set a different 'Extra label' and try again." + ) + + paths = [export_filepath, logfile_exportpath, picture_path, svg_path] + ref_picture_path = ref_svg_path = None + if ref_fig is not None: + ref_picture_path = stem + '_ref.jpg' + ref_svg_path = stem + '_ref.svg' + paths += [ref_picture_path, ref_svg_path] + + export_data = np.column_stack([ + DATA[:, 5], DATA[:, 6], results['OA_interp'], + DATA[:, 7], DATA[:, 8], results['CA_interp'], + DATA[:, 9], DATA[:, 10], results['CAOA_interp'], + ]) + header = ('Position (mm),OA (Data),OA (Fit),Position (mm),CA (Data),CA (Fit),' + 'Position (mm),OACA (Data),OACA (Fit)') + np.savetxt(export_filepath, export_data, delimiter=',', fmt='%.8g', + header=header, comments='', newline='\r\n') + + log_text = build_log_text(cfg, DATA, results, paths) + with open(logfile_exportpath, 'w+', newline='\r\n') as f: + f.write(log_text) + + # NOTE: MATLAB's saveas(..., 'emf') has no direct Matplotlib + # equivalent; an .svg vector file is saved instead as a + # presentation-quality substitute. + _save_at_export_size(fit_fig, picture_path, svg_path) + if ref_fig is not None: + _save_at_export_size(ref_fig, ref_picture_path, ref_svg_path) + + return tuple(paths) diff --git a/zscan_gui.py b/zscan_gui.py new file mode 100644 index 0000000..bdd8495 --- /dev/null +++ b/zscan_gui.py @@ -0,0 +1,1091 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +zscan_gui.py +============ + +Desktop GUI for the Z-scan beam simulation (zscan_core.py). + +Lets you: + * Browse for and select the raw z-scan data file + * Edit every simulation/processing parameter in labeled fields + * Run the simulation (in a background thread so the window doesn't + freeze) and see the two result plots embedded right in the window + * Read off the fit-quality numbers (chi-square, delta-T comparisons) + * Optionally export the fit/data CSV, a log file, and plot images + +Requires: numpy, scipy, matplotlib (tkinter ships with most standard +Python installs; on some Linux distros install it separately, e.g. +`sudo apt install python3-tk`). + +Run with: python zscan_gui.py +""" + +import os +import re +import threading +import traceback +from dataclasses import replace + +import tkinter as tk +import tkinter.font as tkfont +from tkinter import ttk, filedialog, messagebox + +from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg + +from zscan_core import ( + ZScanConfig, + load_and_normalize_data, + peek_column_count, + resolve_endpts, + run_simulation, + refine_fit, + make_reference_figure, + make_fit_figure, + export_results, + build_log_text, + save_settings, + load_settings, + apply_tight_layout, + DEFAULT_ENDPTS_PERCENT, +) + +SETTINGS_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "last_settings.json") + +# Starting width of the left parameter panel, and of the plot pane +# beside it -- together these set the default window width. +PARAM_PANEL_WIDTH = 358 # panel content asks for 355px at 10pt +PLOT_PANE_WIDTH = 800 # + the panel scrollbar, so the window opens ~1173px + +# Width (in characters) of the unit-label column on rows that carry a +# "Refine" checkbox -- wide enough for the longest unit there +# ("m^3/W^2", 7 chars) so every checkbox lands at the same x. +UNIT_COLUMN_CHARS = 8 + +# Width of the label column. The default is sized for the longest +# label in the panel ("d (focus->aperture)"), which leaves the +# Nonlinear Parameters rows -- whose labels are all short, and which +# are the widest rows in the panel because they also carry a unit AND +# a Refine checkbox -- with ~79px of empty column between label and +# entry. Those rows get their own column, sized for "alpha_2". +LABEL_COLUMN_CHARS = 16 +NONLINEAR_LABEL_CHARS = 8 + + +# ----------------------------------------------------------------------- +# Small helper widgets +# ----------------------------------------------------------------------- + +_FLOAT_PARTIAL_RE = re.compile(r'^[+-]?(\d+\.?\d*|\.\d*)?([eE][+-]?\d*)?$') +_INT_PARTIAL_RE = re.compile(r'^[+-]?\d*$') +# Non-negative variants: no leading sign on the overall number, but the +# exponent's own sign (e.g. the "-19" in "5e-19") is still allowed, +# since that just makes a small positive number, not a negative one. +_FLOAT_PARTIAL_NONNEG_RE = re.compile(r'^(\d+\.?\d*|\.\d*)?([eE][+-]?\d*)?$') +_INT_PARTIAL_NONNEG_RE = re.compile(r'^\d*$') + + +class LabeledEntry(ttk.Frame): + """A label + entry pair on one row, with typed get()/set(). When + kind is int or float, keystrokes that would make the field's text + invalid as a (possibly partial, e.g. '-', '1.', '1e-') number are + rejected as they're typed, rather than only failing later when + get() parses the text. str-kind fields (e.g. delimiter, extra + label in the Data File section) are left unrestricted. Pass + allow_negative=False to additionally reject a leading minus sign + (the exponent's own sign, e.g. the '-19' in '5e-19', is still + allowed, since that makes a small positive number). Pass + fit_checkbox=True to add a small "Fit" checkbox at the end of the + row (see fit_enabled()) -- used by the Nonlinear Parameters fields + to mark which ones Refine Fit should optimize.""" + + def __init__(self, parent, label, value, width=14, kind=float, unit="", + allow_negative=True, fit_checkbox=False, label_width=LABEL_COLUMN_CHARS): + super().__init__(parent) + self.kind = kind + self.allow_negative = allow_negative + ttk.Label(self, text=label, width=label_width, anchor="w").pack(side="left") + self.var = tk.StringVar(value=str(value)) + + entry = ttk.Entry(self, textvariable=self.var, width=width) + if kind in (int, float): + vcmd = (self.register(self._validate_numeric_input), "%P") + entry.configure(validate="key", validatecommand=vcmd) + entry.pack(side="left") + self.entry = entry + + if unit: + unit_label = ttk.Label(self, text=unit, foreground="#666") + if fit_checkbox: + # Fixed-width unit column, so the checkboxes still line + # up vertically once they're packed flush against it. + unit_label.configure(width=UNIT_COLUMN_CHARS, anchor="w") + unit_label.pack(side="left", padx=(4, 0)) + + if fit_checkbox: + self.fit_var = tk.BooleanVar(value=False) + # side="left", not "right". Packed right, the checkbox was + # pinned to the far edge of the row, and since rows stretch + # to the width of the WIDEST row in the panel, that opened a + # ragged gap after the unit label on every shorter row. + # Packed left it sits flush, and the row's natural width is + # all the panel has to provide. + ttk.Checkbutton(self, text="Refine", variable=self.fit_var).pack(side="left", padx=(6, 0)) + else: + self.fit_var = None + + def fit_enabled(self) -> bool: + return self.fit_var is not None and self.fit_var.get() + + def set_enabled(self, enabled: bool): + self.entry.configure(state="normal" if enabled else "disabled") + + def is_enabled(self) -> bool: + return str(self.entry.cget("state")) != "disabled" + + def is_empty(self) -> bool: + return self.var.get().strip() == "" + + def _validate_numeric_input(self, proposed_text): + if proposed_text == "": + return True + if self.kind is int: + pattern = _INT_PARTIAL_RE if self.allow_negative else _INT_PARTIAL_NONNEG_RE + else: + pattern = _FLOAT_PARTIAL_RE if self.allow_negative else _FLOAT_PARTIAL_NONNEG_RE + return bool(pattern.match(proposed_text)) + + def get(self): + return self.kind(self.var.get().strip()) + + def set(self, value): + self.var.set(str(value)) + + +class LabeledCheck(ttk.Frame): + def __init__(self, parent, label, value=False, command=None): + super().__init__(parent) + self.var = tk.BooleanVar(value=bool(value)) + cb_kwargs = {"command": command} if command is not None else {} + self.checkbutton = ttk.Checkbutton(self, text=label, variable=self.var, **cb_kwargs) + self.checkbutton.pack(side="left") + + def get(self): + return self.var.get() + + def set(self, value): + self.var.set(bool(value)) + + def set_enabled(self, enabled: bool): + self.checkbutton.configure(state="normal" if enabled else "disabled") + + +class ResizableFigureCanvas: + """ + Embeds a Matplotlib Figure inside `holder` and keeps it letterboxed + (or pillarboxed) at its original aspect ratio as `holder` is + resized -- i.e. the plot grows/shrinks with the window but is never + stretched out of proportion. + """ + + def __init__(self, holder, fig): + self.holder = holder + self.fig = fig + self.aspect = fig.get_figwidth() / fig.get_figheight() + self.dpi = fig.get_dpi() + + self.canvas = FigureCanvasTkAgg(fig, master=holder) + self.widget = self.canvas.get_tk_widget() + self.widget.place(x=0, y=0) + + holder.bind("", self._resize) + holder.update_idletasks() + self._resize() + + def _resize(self, event=None): + if event is not None: + w, h = event.width, event.height + else: + w, h = self.holder.winfo_width(), self.holder.winfo_height() + if w < 2 or h < 2: + return + + if w / h > self.aspect: + new_h = h + new_w = int(round(h * self.aspect)) + else: + new_w = w + new_h = int(round(w / self.aspect)) + + # Enforce a minimum figure width. Below this, the fixed-point- + # size text (titles/labels/ticks/legend) genuinely no longer + # fits no matter how the layout margins are tuned -- tight_layout + # itself gives up in that range. Better to let the plot extend + # past a too-small panel (normal, expected UX) than to render + # illegibly with text clipped inside it. + min_w = int(6.0 * self.dpi) + if new_w < min_w: + new_w = min_w + new_h = int(round(min_w / self.aspect)) + + x, y = (w - new_w) // 2, (h - new_h) // 2 + self.widget.place(x=x, y=y, width=new_w, height=new_h) + + # Explicitly resize the Figure itself (rather than relying on + # the backend's own auto-resize handling) so the plot always + # redraws sharp at its new pixel size. + self.fig.set_size_inches(new_w / self.dpi, new_h / self.dpi, forward=False) + + # Re-run the layout at the new size. Axes margins are fixed + # FRACTIONS of the figure (set once by tight_layout at creation + # time), but text (titles/labels/ticks/legend) is fixed POINT + # sizes -- so shrinking the figure to fit a smaller GUI panel + # leaves those margins without enough absolute room for the + # same text, and it overflows past the figure edge, getting + # clipped by the widget's bounds. Recomputing here keeps the + # whole figure visible at any panel size. + apply_tight_layout(self.fig) + + self.canvas.draw_idle() + + +def add_section(parent, title): + frame = ttk.LabelFrame(parent, text=title, padding=8) + frame.pack(fill="x", padx=8, pady=6) + return frame + + +# ----------------------------------------------------------------------- +# Main application +# ----------------------------------------------------------------------- + +class ZScanApp(tk.Tk): + # Preferred font, with metric-compatible / widely-available fallbacks + # in case a given Linux install doesn't have Liberation Sans (e.g. a + # minimal Fedora spin without the `liberation-fonts` package). + PREFERRED_FONT_FAMILIES = ("Liberation Sans", "DejaVu Sans", "Noto Sans", "Arial", "Helvetica") + FONT_SIZE = 10 + + def __init__(self): + super().__init__() + self.title("Z-Scan Beam Simulation") + self.geometry(f"{PARAM_PANEL_WIDTH + PLOT_PANE_WIDTH}x820") + + self._configure_fonts() + + self.DATA = None + self.norm_OA = None + self.norm_CA = None + self.results = None + self.fit_fig = None + self.ref_fig = None + self.cfg = None + self._data_col_count = None + self._has_imported = False + + self._build_layout() + self._load_previous_settings() + self._on_use_freq_toggle() + self._on_use_ref_toggle() + + def _configure_fonts(self): + """Set every stock Tk/ttk font to 10pt Liberation Sans (falling + back to another common sans-serif family if Liberation Sans + isn't installed on this system) so all widgets -- including + ones that don't take an explicit font= argument -- pick it up + consistently. + + Note on anti-aliasing: Tk has no separate on/off flag for this. + Anti-aliased rendering is handled by the OS's font engine + (Xft/fontconfig on Linux/X11, DirectWrite on Windows, Core Text + on macOS) whenever a scalable TrueType/OpenType family is used, + which is the default on any modern Tk 8.6+ build. On Linux this + is controlled by fontconfig / your desktop environment's font + settings, not by this script. + """ + # Tk/X11 font-family names are frequently reported in lowercase + # (e.g. "liberation sans" rather than "Liberation Sans"), so + # match case-insensitively but keep the exact string Tk itself + # reports when actually configuring the font. + available = {f.lower(): f for f in tkfont.families(self)} + chosen = None + for preferred in self.PREFERRED_FONT_FAMILIES: + if preferred.lower() in available: + chosen = available[preferred.lower()] + break + + if chosen is None: + chosen = "TkDefaultFont" + print(f"[zscan_gui] Warning: none of {self.PREFERRED_FONT_FAMILIES} were found " + f"via Tk's font list; falling back to the system default font.") + elif chosen.lower() != self.PREFERRED_FONT_FAMILIES[0].lower(): + print(f"[zscan_gui] Note: '{self.PREFERRED_FONT_FAMILIES[0]}' not found; " + f"using '{chosen}' instead. (On Fedora: sudo dnf install liberation-fonts)") + + self.ui_font = (chosen, self.FONT_SIZE) + + for name in ("TkDefaultFont", "TkTextFont", "TkFixedFont", "TkMenuFont", + "TkHeadingFont", "TkCaptionFont", "TkSmallCaptionFont", + "TkIconFont", "TkTooltipFont"): + try: + tkfont.nametofont(name).configure(family=chosen, size=self.FONT_SIZE) + except tk.TclError: + pass + self.option_add("*Font", self.ui_font) + style = ttk.Style(self) + style.configure(".", font=self.ui_font) + + # ------------------------------------------------------------------ + # Layout + # ------------------------------------------------------------------ + + def _build_layout(self): + outer = ttk.PanedWindow(self, orient="horizontal") + outer.pack(fill="both", expand=True) + + # Both panes are added up front so the left/right order of the + # PanedWindow doesn't depend on the order their contents are + # built in -- the right pane's action bar has to be built + # FIRST, because _build_param_fields ends by attaching traces + # that call _update_run_button_state, which needs self.run_button + # to already exist. + # NOTE: the width has to go on the CANVAS, not on left_container. + # A Frame sizes itself to its packed children, so ttk.Frame(..., + # width=N) here is silently ignored -- the old width=380 never + # took effect at all, and the panel just inherited tk.Canvas's + # 394px default. That default was narrow enough to cut the + # "Refine" checkboxes off the right-hand end of the Nonlinear + # Parameters rows until the user dragged the sash wider. + # PARAM_PANEL_WIDTH is the visible viewport; the scrollbar sits + # outside it, so the pane ends up ~15px wider still. The sash + # remains user-draggable -- this only sets where it starts. + left_container = ttk.Frame(outer) + outer.add(left_container, weight=0) + right = ttk.Frame(outer) + outer.add(right, weight=1) + + # --- right: action bar + notebook of plots + log --- + self._build_action_bar(right) + + self.notebook = ttk.Notebook(right) + self.notebook.pack(fill="both", expand=True, padx=6, pady=(6, 0)) + + self.tab_ref = ttk.Frame(self.notebook) + self.tab_fit = ttk.Frame(self.notebook) + self.tab_log = ttk.Frame(self.notebook) + self.notebook.add(self.tab_ref, text="Referenced / Normalized") + self.notebook.add(self.tab_fit, text="Fit Results") + self.notebook.add(self.tab_log, text="Fit Quality / Log") + + self.log_text = tk.Text(self.tab_log, wrap="word", font=self.ui_font) + self.log_text.pack(fill="both", expand=True, padx=6, pady=6) + + self.ref_canvas_holder = ttk.Frame(self.tab_ref) + self.ref_canvas_holder.pack(fill="both", expand=True) + self.fit_canvas_holder = ttk.Frame(self.tab_fit) + self.fit_canvas_holder.pack(fill="both", expand=True) + + # --- bottom status bar --- + status_bar = ttk.Frame(right) + status_bar.pack(fill="x", padx=6, pady=6) + self.status_var = tk.StringVar(value="Ready.") + ttk.Label(status_bar, textvariable=self.status_var).pack(side="left") + self.progress = ttk.Progressbar(status_bar, mode="indeterminate", length=160) + self.progress.pack(side="right") + + # --- left: scrollable parameter panel --- + canvas = tk.Canvas(left_container, borderwidth=0, highlightthickness=0, + width=PARAM_PANEL_WIDTH) + scrollbar = ttk.Scrollbar(left_container, orient="vertical", command=canvas.yview) + self.param_frame = ttk.Frame(canvas) + self.param_frame.bind( + "", lambda _event: canvas.configure(scrollregion=canvas.bbox("all")) + ) + canvas.create_window((0, 0), window=self.param_frame, anchor="nw") + canvas.configure(yscrollcommand=scrollbar.set) + canvas.pack(side="left", fill="both", expand=True) + scrollbar.pack(side="right", fill="y") + self.param_canvas = canvas + + self._build_param_fields(self.param_frame) + + def _build_action_bar(self, parent): + """The five action buttons, in one row directly above the plot + pane, left to right in the order they're used: Import -> Run + Simulation -> Refine Fit -> Export, then Exit. Laid out with + grid rather than pack so `uniform` can hold all five columns to + the same width regardless of label length, and so they keep that + width as the pane is resized. + + Every button carries the SAME 3px padding on both sides and the + outer 3px is put on the frame instead. Padding the two end + buttons asymmetrically (0 outside, 3 inside) would leave them 3px + wider than the rest, since uniform equalizes the columns, not the + widgets inside them. 3 + 3 also lines the row's outer edges up + with the notebook's own 6px padx below it. + """ + bar = ttk.Frame(parent) + bar.pack(fill="x", padx=3, pady=(6, 0)) + + self.import_button = ttk.Button(bar, text="Import", command=self._on_import) + self.run_button = ttk.Button(bar, text="Run Simulation", command=self._on_run, + state="disabled") + self.refine_button = ttk.Button(bar, text="Refine Fit", command=self._on_refine_fit, + state="disabled") + self.export_button = ttk.Button(bar, text="Export...", command=self._on_export, + state="disabled") + self.exit_button = ttk.Button(bar, text="Exit", command=self._on_exit) + + # Exit is in the uniform group with the other four, so all five + # are the same width and share the same 3px padding. It is the + # one button here that ends the session rather than advancing + # the workflow, so it is placed last, furthest from Import. + buttons = (self.import_button, self.run_button, self.refine_button, + self.export_button, self.exit_button) + for column, button in enumerate(buttons): + button.grid(row=0, column=column, sticky="ew", padx=3) + bar.columnconfigure(column, weight=1, uniform="action_buttons") + + def _build_param_fields(self, parent): + # --- File --- + sec = add_section(parent, "Data File") + self.filepath_var = tk.StringVar(value="") + row = ttk.Frame(sec) + row.pack(fill="x", pady=2) + ttk.Entry(row, textvariable=self.filepath_var, width=28).pack(side="left", fill="x", expand=True) + ttk.Button(row, text="Browse...", command=self._browse_file).pack(side="left", padx=(4, 0)) + self.delimiter = LabeledEntry(sec, "Delimiter", "", width=10, kind=str, + unit='(blank = auto)') + self.delimiter.pack(fill="x", pady=2) + self.extra_label = LabeledEntry(sec, "Extra label", "", width=14, kind=str) + self.extra_label.pack(fill="x", pady=2) + + sec = add_section(parent, "Data Columns (1-indexed)") + self.z_col = LabeledEntry(sec, "z column", 1, kind=int, allow_negative=False) + self.CA_col = LabeledEntry(sec, "CA column", 2, kind=int, allow_negative=False) + self.OA_col = LabeledEntry(sec, "OA column", 5, kind=int, allow_negative=False) + self.REF_col = LabeledEntry(sec, "REF column", 8, kind=int, allow_negative=False) + self.FREQ_col = LabeledEntry(sec, "FREQ column", 4, kind=int, allow_negative=False) + for w in (self.z_col, self.CA_col, self.OA_col, self.REF_col, self.FREQ_col): + w.pack(fill="x", pady=2) + + sec = add_section(parent, "Processing Flags") + self.use_ref = LabeledCheck(sec, "Use reference channel", True, command=self._on_use_ref_toggle) + self.use_freq = LabeledCheck(sec, "Use frequency channel", False, command=self._on_use_freq_toggle) + self.flip_z = LabeledCheck(sec, "flip_z (flip z-axis)", True) + self.do_norm_OA = LabeledCheck(sec, "Normalize OA (slope fit)", True) + self.do_norm_CA = LabeledCheck(sec, "Normalize CA (slope fit)", True) + self.flip_OA = LabeledCheck(sec, "flip_OA", False) + self.flip_CA = LabeledCheck(sec, "flip_CA", False) + self.flip_REF = LabeledCheck(sec, "flip_REF", False) + self.flip_OA_disp = LabeledCheck(sec, "flip_OA_disp", False) + self.flip_CA_disp = LabeledCheck(sec, "flip_CA_disp", False) + self.show_CA = LabeledCheck(sec, "Show CA (else OA/CA)", True) + for w in (self.use_ref, self.use_freq, self.flip_z, self.do_norm_OA, self.do_norm_CA, self.flip_OA, + self.flip_CA, self.flip_REF, self.flip_OA_disp, self.flip_CA_disp, self.show_CA): + w.pack(fill="x", pady=1) + + sec = add_section(parent, "Nonlinear Parameters") + self.n_2 = LabeledEntry(sec, "n_2", 10e-19, unit="m^2/W", fit_checkbox=True, + label_width=NONLINEAR_LABEL_CHARS) + self.n_3 = LabeledEntry(sec, "n_3", 0, unit="m^4/W^2", fit_checkbox=True, + label_width=NONLINEAR_LABEL_CHARS) + self.n_4 = LabeledEntry(sec, "n_4", 0, unit="m^6/W^3", fit_checkbox=True, + label_width=NONLINEAR_LABEL_CHARS) + self.alpha_2 = LabeledEntry(sec, "alpha_2", 0, unit="m/W", fit_checkbox=True, + label_width=NONLINEAR_LABEL_CHARS) + self.alpha_3 = LabeledEntry(sec, "alpha_3", 0, unit="m^3/W^2", fit_checkbox=True, + label_width=NONLINEAR_LABEL_CHARS) + self.alpha_4 = LabeledEntry(sec, "alpha_4", 2.2e-43, unit="m^5/W^3", fit_checkbox=True, + label_width=NONLINEAR_LABEL_CHARS) + for w in (self.n_2, self.n_3, self.n_4, self.alpha_2, self.alpha_3, self.alpha_4): + w.pack(fill="x", pady=2) + + sec = add_section(parent, "z-Position Offsets [mm]") + self.Delta_z_OA = LabeledEntry(sec, "Delta_z_OA", 0.05) + self.Delta_z_CA = LabeledEntry(sec, "Delta_z_CA", 0.23) + self.Delta_z_OACA = LabeledEntry(sec, "Delta_z_OACA", 0.0) + for w in (self.Delta_z_OA, self.Delta_z_CA, self.Delta_z_OACA): + w.pack(fill="x", pady=2) + + sec = add_section(parent, "Sample Parameters") + self.n = LabeledEntry(sec, "n (linear)", 3.0337, allow_negative=False) + self.L = LabeledEntry(sec, "L", 0.188, unit="mm", allow_negative=False) + self.T_lin = LabeledEntry(sec, "T_lin", 1.0, allow_negative=False) + for w in (self.n, self.L, self.T_lin): + w.pack(fill="x", pady=2) + + sec = add_section(parent, "Laser Parameters") + self.E = LabeledEntry(sec, "E (pulse energy)", 180, unit="nJ", allow_negative=False) + self.lambda_ = LabeledEntry(sec, "lambda", 2000, unit="nm", allow_negative=False) + self.w_0 = LabeledEntry(sec, "w_0 (waist)", 19, unit="um", allow_negative=False) + self.tau_FWHM = LabeledEntry(sec, "tau_FWHM", 50, unit="fs", allow_negative=False) + self.M2 = LabeledEntry(sec, "M^2", 1.0, allow_negative=False) + for w in (self.E, self.lambda_, self.w_0, self.tau_FWHM, self.M2): + w.pack(fill="x", pady=2) + + sec = add_section(parent, "Measurement Parameters") + self.S = LabeledEntry(sec, "S (aperture trans.)", 0.33, allow_negative=False) + self.d = LabeledEntry(sec, "d (focus->aperture)", 100, unit="cm", allow_negative=False) + for w in (self.S, self.d): + w.pack(fill="x", pady=2) + + sec = add_section(parent, "Error Estimates (fraction)") + self.E_err = LabeledEntry(sec, "E_err", 0.10, allow_negative=False) + self.w_err = LabeledEntry(sec, "w_err", 0.10, allow_negative=False) + self.tau_err = LabeledEntry(sec, "tau_err", 0.10, allow_negative=False) + for w in (self.E_err, self.w_err, self.tau_err): + w.pack(fill="x", pady=2) + + sec = add_section(parent, "Simulation Parameters") + self.z_points = LabeledEntry(sec, "z_points (even)", 76, kind=int, allow_negative=False) + self.r_points = LabeledEntry(sec, "r_points", 500, kind=int, allow_negative=False) + self.r_max = LabeledEntry(sec, "r_max", 3, unit="w", allow_negative=False) + self.t_points = LabeledEntry(sec, "t_points", 50, kind=int, allow_negative=False) + self.t_max = LabeledEntry(sec, "t_max", 3, unit="tau", allow_negative=False) + self.ra_points = LabeledEntry(sec, "ra_points", 50, kind=int, allow_negative=False) + # "% per side" measures 67px, exactly the space left over before + # the Nonlinear rows stop being the panel's widest -- so the + # unit is spelled out at no cost to the panel width. + self.endpts_percent = LabeledEntry(sec, "endpts", DEFAULT_ENDPTS_PERCENT, kind=float, + allow_negative=False, unit="% per side") + self.max_iterations = LabeledEntry(sec, "Max iterations", 100, kind=int, allow_negative=False) + for w in (self.z_points, self.r_points, self.r_max, self.t_points, self.t_max, self.ra_points, + self.endpts_percent, self.max_iterations): + w.pack(fill="x", pady=2) + ttk.Label( + sec, + text="Memory ~ r_points x ra_points x t_points x z_points x 16 bytes.\n" + "Large grids (defaults) can use several GB of RAM.", + foreground="#a33", wraplength=PARAM_PANEL_WIDTH - 60, justify="left", + ).pack(fill="x", pady=(4, 0)) + + # The Import / Run / Refine / Export / Exit buttons live in the + # action bar above the plot pane (_build_action_bar), not here. + + # Every numeric input field outside the Data File section -- + # Run Simulation stays disabled if any of these is left empty. + self._required_entry_fields = [ + self.z_col, self.CA_col, self.OA_col, self.REF_col, self.FREQ_col, + self.n_2, self.n_3, self.n_4, self.alpha_2, self.alpha_3, self.alpha_4, + self.Delta_z_OA, self.Delta_z_CA, self.Delta_z_OACA, + self.n, self.L, self.T_lin, + self.E, self.lambda_, self.w_0, self.tau_FWHM, self.M2, + self.S, self.d, + self.E_err, self.w_err, self.tau_err, + self.z_points, self.r_points, self.r_max, self.t_points, self.t_max, self.ra_points, + self.endpts_percent, + ] + for field_widget in self._required_entry_fields: + field_widget.var.trace_add("write", lambda *_args: self._update_run_button_state()) + + # Data Columns + Processing Flags -- once Import has been used + # at least once, changing any of these live-refreshes the + # Referenced/Normalized plot without needing to click Import + # again. show_CA is deliberately absent: it selects which series + # the FIT figure's right-hand panel shows and never reaches + # make_reference_figure, so refreshing on it just re-read the + # data file and redrew an identical plot. + self._reference_refresh_fields = [ + self.z_col, self.CA_col, self.OA_col, self.REF_col, self.FREQ_col, + self.use_ref, self.use_freq, self.flip_z, self.do_norm_OA, self.do_norm_CA, + self.flip_OA, self.flip_CA, self.flip_REF, self.flip_OA_disp, self.flip_CA_disp, + self.endpts_percent, + ] + for field_widget in self._reference_refresh_fields: + field_widget.var.trace_add("write", lambda *_args: self._refresh_reference_plot()) + + def _on_use_freq_toggle(self): + """Enables/disables the FREQ column field based on the 'Use + frequency channel' checkbox -- the FREQ column's data isn't + actually used in any calculation, so this only controls + whether the field is editable, not any computation. When the + imported file has exactly 4 columns, use_ref and use_freq are + mutually exclusive (only one may be checked at a time), since + there's only one "extra" column beyond z/CA/OA for either a + reference or a frequency channel to occupy.""" + if self._data_col_count == 4 and self.use_freq.get() and self.use_ref.get(): + self.use_ref.set(False) + self.REF_col.set_enabled(False) + self.FREQ_col.set_enabled(self.use_freq.get()) + + def _on_use_ref_toggle(self): + """Enables/disables the REF column field based on the 'Use + reference channel' checkbox. See _on_use_freq_toggle for the + 4-column mutual-exclusion behavior.""" + if self._data_col_count == 4 and self.use_ref.get() and self.use_freq.get(): + self.use_freq.set(False) + self.FREQ_col.set_enabled(False) + self.REF_col.set_enabled(self.use_ref.get()) + + def _apply_column_count_constraint(self, n_cols): + """Constrains use_ref/use_freq based on how many columns the + imported file actually has: + - 3 columns (just z, CA, OA): neither flag can be used -- + forced off and disabled. + - 4 columns: only one of the two may be enabled at a time + (see the mutual exclusion in the toggle handlers above). + - 5+ columns: no restriction, both may be enabled. + """ + self._data_col_count = n_cols + if n_cols <= 3: + self.use_ref.set(False) + self.use_freq.set(False) + self.use_ref.set_enabled(False) + self.use_freq.set_enabled(False) + elif n_cols == 4: + self.use_ref.set_enabled(True) + self.use_freq.set_enabled(True) + if self.use_ref.get() and self.use_freq.get(): + self.use_freq.set(False) + else: + self.use_ref.set_enabled(True) + self.use_freq.set_enabled(True) + + self._on_use_ref_toggle() + self._on_use_freq_toggle() + + # ------------------------------------------------------------------ + # Actions + # ------------------------------------------------------------------ + + def _browse_file(self): + path = filedialog.askopenfilename( + title="Select z-scan data file", + filetypes=[("Text/data files", "*.txt *.dat *.csv"), ("All files", "*.*")], + ) + if path: + self.filepath_var.set(path) + + def _gather_config(self) -> ZScanConfig: + return ZScanConfig( + import_filepath=self.filepath_var.get(), + delimiter=self.delimiter.get(), + extra_label=self.extra_label.get(), + z_col=self.z_col.get(), CA_col=self.CA_col.get(), OA_col=self.OA_col.get(), + REF_col=self.REF_col.get(), FREQ_col=self.FREQ_col.get(), + use_ref=self.use_ref.get(), use_freq=self.use_freq.get(), flip_z=int(self.flip_z.get()), + do_norm_OA=self.do_norm_OA.get(), do_norm_CA=self.do_norm_CA.get(), + flip_OA=int(self.flip_OA.get()), flip_CA=int(self.flip_CA.get()), + flip_REF=int(self.flip_REF.get()), + flip_OA_disp=int(self.flip_OA_disp.get()), flip_CA_disp=int(self.flip_CA_disp.get()), + show_CA=self.show_CA.get(), + n_2=self.n_2.get(), n_3=self.n_3.get(), n_4=self.n_4.get(), + alpha_2=self.alpha_2.get(), alpha_3=self.alpha_3.get(), alpha_4=self.alpha_4.get(), + Delta_z_OA=self.Delta_z_OA.get(), Delta_z_CA=self.Delta_z_CA.get(), + Delta_z_OACA=self.Delta_z_OACA.get(), + n=self.n.get(), L=self._clean_float(self.L.get() * 1e-3), T_lin=self.T_lin.get(), + E=self._clean_float(self.E.get() * 1e-9), lambda_=self._clean_float(self.lambda_.get() * 1e-9), + w_0=self._clean_float(self.w_0.get() * 1e-6), + tau_FWHM=self._clean_float(self.tau_FWHM.get() * 1e-15), M2=self.M2.get(), + S=self.S.get(), d=self._clean_float(self.d.get() * 1e-2), + E_err=self.E_err.get(), w_err=self.w_err.get(), tau_err=self.tau_err.get(), + z_points=self.z_points.get(), r_points=self.r_points.get(), r_max=self.r_max.get(), + t_points=self.t_points.get(), t_max=self.t_max.get(), ra_points=self.ra_points.get(), + endpts_percent=self.endpts_percent.get(), + max_iterations=self.max_iterations.get(), + ) + + @staticmethod + def _clean_float(value, sig_figs=12): + """Rounds away floating-point round-trip noise from the + unit-conversion multiply/divide pairs (e.g. 19 um -> 1.9e-05 m + -> back to um can land on 18.999999999999996 instead of 19) + while preserving all real precision a user could plausibly + have typed. 12 significant figures is well beyond any + practical input precision but comfortably below float64's + 15-17 digit noise floor.""" + return float(f"{value:.{sig_figs}g}") + + def _apply_config_to_fields(self, cfg: ZScanConfig): + """Populates every field widget from a loaded ZScanConfig -- + the exact inverse of _gather_config, including reversing the + display-unit conversions (E/lambda/w_0/tau_FWHM/L/d).""" + self.filepath_var.set(cfg.import_filepath) + self.delimiter.set(cfg.delimiter) + self.extra_label.set(cfg.extra_label) + self.z_col.set(cfg.z_col) + self.CA_col.set(cfg.CA_col) + self.OA_col.set(cfg.OA_col) + self.REF_col.set(cfg.REF_col) + self.FREQ_col.set(cfg.FREQ_col) + self.use_ref.set(cfg.use_ref) + self.use_freq.set(cfg.use_freq) + self.flip_z.set(cfg.flip_z) + self.do_norm_OA.set(cfg.do_norm_OA) + self.do_norm_CA.set(cfg.do_norm_CA) + self.flip_OA.set(cfg.flip_OA) + self.flip_CA.set(cfg.flip_CA) + self.flip_REF.set(cfg.flip_REF) + self.flip_OA_disp.set(cfg.flip_OA_disp) + self.flip_CA_disp.set(cfg.flip_CA_disp) + self.show_CA.set(cfg.show_CA) + self.n_2.set(cfg.n_2) + self.n_3.set(cfg.n_3) + self.n_4.set(cfg.n_4) + self.alpha_2.set(cfg.alpha_2) + self.alpha_3.set(cfg.alpha_3) + self.alpha_4.set(cfg.alpha_4) + self.Delta_z_OA.set(cfg.Delta_z_OA) + self.Delta_z_CA.set(cfg.Delta_z_CA) + self.Delta_z_OACA.set(cfg.Delta_z_OACA) + self.n.set(cfg.n) + self.L.set(self._clean_float(cfg.L * 1e3)) + self.T_lin.set(cfg.T_lin) + self.E.set(self._clean_float(cfg.E * 1e9)) + self.lambda_.set(self._clean_float(cfg.lambda_ * 1e9)) + self.w_0.set(self._clean_float(cfg.w_0 * 1e6)) + self.tau_FWHM.set(self._clean_float(cfg.tau_FWHM * 1e15)) + self.M2.set(cfg.M2) + self.S.set(cfg.S) + self.d.set(self._clean_float(cfg.d * 1e2)) + self.E_err.set(cfg.E_err) + self.w_err.set(cfg.w_err) + self.tau_err.set(cfg.tau_err) + self.z_points.set(cfg.z_points) + self.r_points.set(cfg.r_points) + self.r_max.set(cfg.r_max) + self.t_points.set(cfg.t_points) + self.t_max.set(cfg.t_max) + self.ra_points.set(cfg.ra_points) + self.endpts_percent.set(cfg.endpts_percent) + self.max_iterations.set(cfg.max_iterations) + + def _load_previous_settings(self): + """Loads last_settings.json (saved on the previous exit) and + restores every field from it. If the file doesn't exist, is + corrupt, or otherwise can't be loaded, this silently leaves + every field at the hardcoded defaults they were already built + with -- no error shown, since a missing/bad settings file on + first run (or after a manual delete) is entirely normal.""" + if not os.path.isfile(SETTINGS_PATH): + return + try: + cfg = load_settings(SETTINGS_PATH) + self._apply_config_to_fields(cfg) + print(f"zscan_gui: previous settings loaded from {SETTINGS_PATH}.") + except Exception as exc: + print(f"zscan_gui: could not load {SETTINGS_PATH} ({exc}); using defaults.") + + def _on_exit(self): + try: + save_settings(self._gather_config(), SETTINGS_PATH) + except Exception as exc: + print(f"zscan_gui: failed to save settings to {SETTINGS_PATH}: {exc}") + self.destroy() + + def _on_import(self): + """Loads and normalizes the data file and immediately shows it + in the Referenced/Normalized tab, using the exact same figure + (make_reference_figure) that "Run Simulation" populates that + tab with -- so the two look identical, just available sooner, + before running the full (potentially slow) simulation.""" + try: + cfg = self._gather_config() + except Exception as exc: + messagebox.showerror("Invalid parameter", str(exc)) + return + + if not cfg.import_filepath or not os.path.isfile(cfg.import_filepath): + messagebox.showerror("File not found", "Please select a valid data file.") + return + + try: + n_cols = peek_column_count(cfg.import_filepath, cfg.delimiter) + except Exception: + tb = traceback.format_exc() + messagebox.showerror("Import failed", tb.strip().splitlines()[-1]) + return + + # Constrain use_ref/use_freq to what the file's actual column + # count allows *before* the full load, since a stale flag + # pointing past a smaller file's columns would otherwise fail + # with an out-of-bounds index. + self._apply_column_count_constraint(n_cols) + cfg = self._gather_config() + + try: + DATA = self._load_reference(cfg) + except Exception: + tb = traceback.format_exc() + messagebox.showerror("Import failed", tb.strip().splitlines()[-1]) + return + + self.notebook.select(self.tab_ref) + # The percentage is reported alongside the count it resolved to, + # since the count depends on this file's number of points. + self.status_var.set( + f"Imported {DATA.shape[0]} points ({n_cols} columns) from " + f"{os.path.basename(cfg.import_filepath)}; " + f"endpts = {cfg.endpts_percent:g}% " + f"({resolve_endpts(cfg.endpts_percent, DATA.shape[0])} points per side)." + ) + self._has_imported = True + self._update_run_button_state() + + def _load_reference(self, cfg: ZScanConfig): + """Load cfg's data file and show it in the Referenced/Normalized + tab, keeping self.DATA / self.norm_* / self.cfg / self.ref_fig in + step. Shared by Import and the live refresh, which previously + each did this inline -- and both left self.ref_fig pointing at + whatever figure the last Run had built, so exporting after + changing a column or a processing flag wrote out a reference + image that no longer matched the plot on screen.""" + DATA, norm_OA, norm_CA = load_and_normalize_data(cfg) + self.DATA, self.norm_OA, self.norm_CA, self.cfg = DATA, norm_OA, norm_CA, cfg + self.ref_fig = make_reference_figure(DATA, norm_OA, norm_CA, + cfg.do_norm_OA, cfg.do_norm_CA) + self._embed_figure(self.ref_canvas_holder, self.ref_fig) + return DATA + + def _update_run_button_state(self): + """Run Simulation stays disabled until a file has been + successfully imported AND every required field (everything + outside the Data File section) has a non-empty value. Fields + currently disabled (e.g. REF column while 'Use reference + channel' is unchecked) are skipped, since their value doesn't + matter to the simulation while they're inactive.""" + if not self._has_imported: + self.run_button.config(state="disabled") + return + if any(w.is_enabled() and w.is_empty() for w in self._required_entry_fields): + self.run_button.config(state="disabled") + return + self.run_button.config(state="normal") + + def _refresh_reference_plot(self): + """Re-loads the data file and redraws the Referenced/Normalized + plot with the current Data Columns / Processing Flags settings. + Only takes effect after Import has been used at least once; + before that, or if the current settings are momentarily invalid + (e.g. mid-edit of a column number, or a column index the file + doesn't have), this silently does nothing and leaves whatever + was last successfully shown in place.""" + if not self._has_imported: + return + try: + cfg = self._gather_config() + except Exception: + return + if not cfg.import_filepath or not os.path.isfile(cfg.import_filepath): + return + try: + self._load_reference(cfg) + except Exception: + return + + def _on_run(self): + try: + cfg = self._gather_config() + except Exception as exc: + messagebox.showerror("Invalid parameter", str(exc)) + return + + if not cfg.import_filepath or not os.path.isfile(cfg.import_filepath): + messagebox.showerror("File not found", "Please select a valid data file.") + return + if cfg.z_points % 2 != 0: + if not messagebox.askyesno("z_points is odd", + "z_points should normally be even. Continue anyway?"): + return + + self.run_button.config(state="disabled") + self.refine_button.config(state="disabled") + self.export_button.config(state="disabled") + self.status_var.set("Running simulation...") + self.progress.start(12) + self.log_text.delete("1.0", "end") + + thread = threading.Thread(target=self._run_worker, args=(cfg,), daemon=True) + thread.start() + + def _run_worker(self, cfg: ZScanConfig): + try: + DATA, norm_OA, norm_CA = load_and_normalize_data(cfg) + results = run_simulation(cfg, DATA) + ref_fig = make_reference_figure(DATA, norm_OA, norm_CA, cfg.do_norm_OA, cfg.do_norm_CA) + fit_fig = make_fit_figure(cfg, DATA, results) + + self.DATA, self.norm_OA, self.norm_CA = DATA, norm_OA, norm_CA + self.results, self.fit_fig, self.ref_fig, self.cfg = results, fit_fig, ref_fig, cfg + + self.after(0, self._on_run_success) + except Exception: + tb = traceback.format_exc() + self.after(0, self._on_run_error, tb) + + def _on_run_success(self): + # Reads the results off self rather than taking them as + # arguments: the worker has already stored every one of them + # there, so passing the same objects through as well was two + # copies of the same handoff. Only ever one run is in flight -- + # Run is disabled for the duration. + self._embed_figure(self.ref_canvas_holder, self.ref_fig) + self._embed_figure(self.fit_canvas_holder, self.fit_fig) + + self.log_text.delete("1.0", "end") + self.log_text.insert("1.0", build_log_text(self.cfg, self.DATA, self.results)) + + self.progress.stop() + self.status_var.set("Done.") + self._update_run_button_state() + self.refine_button.config(state="normal") + self.export_button.config(state="normal") + self.notebook.select(self.tab_fit) + + def _on_run_error(self, tb_text): + self.progress.stop() + self.status_var.set("Error.") + self._update_run_button_state() + self.refine_button.config(state="disabled") + self.export_button.config(state="disabled") + self.log_text.delete("1.0", "end") + self.log_text.insert("1.0", tb_text) + self.notebook.select(self.tab_log) + messagebox.showerror("Simulation failed", tb_text.strip().splitlines()[-1]) + + def _on_refine_fit(self): + """Runs a downhill-simplex (Nelder-Mead) search over whichever + nonlinear parameters have their 'Refine' checkbox ticked, to + minimize the RMSE between the simulated fit and the actual + data -- requires a prior successful Run Simulation, since it + refines starting from that result's data and parameters.""" + if self.results is None or self.DATA is None or self.cfg is None: + messagebox.showerror("Nothing to refine", "Run the simulation first.") + return + + param_names = [name for name in ("n_2", "n_3", "n_4", "alpha_2", "alpha_3", "alpha_4") + if getattr(self, name).fit_enabled()] + if not param_names: + messagebox.showerror( + "No parameters selected", + "Check the 'Refine' box next to at least one nonlinear parameter to refine.", + ) + return + + try: + cfg = self._gather_config() + except Exception as exc: + messagebox.showerror("Invalid parameter", str(exc)) + return + + self.run_button.config(state="disabled") + self.refine_button.config(state="disabled") + self.export_button.config(state="disabled") + self.status_var.set(f"Refining fit ({', '.join(param_names)})...") + self.progress.start(12) + + thread = threading.Thread( + target=self._refine_fit_worker, args=(cfg, param_names, cfg.max_iterations), daemon=True + ) + thread.start() + + def _refine_fit_worker(self, cfg: ZScanConfig, param_names, max_iter): + def progress_callback(iteration, rmse): + self.after(0, self.status_var.set, f"Refining fit... iteration {iteration}, RMSE={rmse:.4g}") + + try: + best_cfg, best_results, opt_result = refine_fit( + cfg, self.DATA, param_names, max_iter=max_iter, progress_callback=progress_callback, + ) + + # Round only the just-optimized parameters to 6 significant + # figures (Nelder-Mead's raw output has far more precision + # than is physically meaningful), then re-run the simulation + # at those rounded values so the displayed fields, plots and + # log all stay consistent with each other -- rather than + # showing a rounded number next to a plot/log still + # reflecting the optimizer's full-precision internal result. + # Done here in the worker, not in the _on_refine_success + # callback: that callback runs on the Tk main thread, where + # a full extra run_simulation froze the window for as long + # as a single simulation takes. + rounded_kwargs = {name: self._clean_float(getattr(best_cfg, name), sig_figs=6) + for name in param_names} + best_cfg = replace(best_cfg, **rounded_kwargs) + self.after(0, self.status_var.set, "Re-running at rounded parameter values...") + best_results = run_simulation(best_cfg, self.DATA) + + self.after(0, self._on_refine_success, best_cfg, best_results, opt_result, param_names) + except Exception: + tb = traceback.format_exc() + self.after(0, self._on_refine_error, tb) + + def _on_refine_success(self, best_cfg: ZScanConfig, best_results, opt_result, param_names): + # best_cfg/best_results already come in rounded and re-run -- + # see _refine_fit_worker. + for name in param_names: + getattr(self, name).set(getattr(best_cfg, name)) + + # Only the nonlinear parameters changed, and the reference + # figure is built from the data and the normalization flags -- + # none of which refining touches. Rebuilding it here produced an + # identical figure. + fit_fig = make_fit_figure(best_cfg, self.DATA, best_results) + self._embed_figure(self.fit_canvas_holder, fit_fig) + + self.results, self.fit_fig, self.cfg = best_results, fit_fig, best_cfg + + self.log_text.delete("1.0", "end") + self.log_text.insert("1.0", build_log_text(best_cfg, self.DATA, best_results)) + + self.progress.stop() + state_word = "converged" if opt_result.success else "stopped (did not fully converge)" + self.status_var.set( + f"Refine Fit {state_word} after {opt_result.nit} iterations, RMSE={opt_result.fun:.4g}." + ) + self._update_run_button_state() + self.refine_button.config(state="normal") + self.export_button.config(state="normal") + self.notebook.select(self.tab_fit) + + def _on_refine_error(self, tb_text): + self.progress.stop() + self.status_var.set("Refine Fit failed.") + self._update_run_button_state() + self.refine_button.config(state="normal") + self.export_button.config(state="normal") + self.log_text.delete("1.0", "end") + self.log_text.insert("1.0", tb_text) + self.notebook.select(self.tab_log) + messagebox.showerror("Refine Fit failed", tb_text.strip().splitlines()[-1]) + + def _on_export(self): + if self.results is None: + return + try: + export_paths = export_results(self.cfg, self.DATA, self.results, self.fit_fig, self.ref_fig) + except Exception: + tb = traceback.format_exc() + messagebox.showerror("Export failed", tb.strip().splitlines()[-1]) + return + + self.status_var.set("Export complete.") + # Regenerated from build_log_text with the export paths, rather + # than appending an "Exported files:" block to whatever is + # currently on screen -- appending stacked a fresh duplicate + # block on every repeat export, and formatted it differently + # from the identical listing inside the exported _log.txt. + self.log_text.delete("1.0", "end") + self.log_text.insert("1.0", build_log_text(self.cfg, self.DATA, self.results, export_paths)) + self.notebook.select(self.tab_log) + messagebox.showinfo("Export complete", "Exported:\n" + "\n".join(export_paths)) + + def _embed_figure(self, holder, fig): + for child in holder.winfo_children(): + child.destroy() + + view = ResizableFigureCanvas(holder, fig) + + # Keep a strong reference alive (Tkinter/Matplotlib won't hold + # one for us, and a garbage-collected canvas stops redrawing). + if holder is self.ref_canvas_holder: + self._ref_view = view + else: + self._fit_view = view + + +if __name__ == "__main__": + app = ZScanApp() + app.protocol("WM_DELETE_WINDOW", app._on_exit) + app.mainloop()