Files
2026-09-24 01:31:32 +00:00

1212 lines
52 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Z-Scan Beam Simulation - simulation engine
#
# Copyright (C) 2019-2026 Manuel R. Ferdinandus
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
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.
"""
__version__ = "1.5"
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
# Operation modes. Fitting is the program's original behaviour: a
# measured scan is imported and the simulation compared against it.
# Simulation runs the same physics with no data at all, showing the
# calculated signals alone -- so there is nothing to normalize, fit or
# compare with, and the z range comes from a parameter rather than from
# the data's own extent.
OPERATION_FITTING = "fitting"
OPERATION_SIMULATION = "simulation"
OPERATIONS = (OPERATION_FITTING, OPERATION_SIMULATION)
# Half-width of the simulated scan in Simulation mode, in Rayleigh
# ranges: the curves span -sim_z_range_z0 .. +sim_z_range_z0 times z_0.
DEFAULT_SIM_Z_RANGE_Z0 = 15.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
# --- operation mode ---
operation_mode: str = OPERATION_FITTING
sim_z_range_z0: float = DEFAULT_SIM_Z_RANGE_Z0 # Simulation mode only
# =============================================================================
# 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=None):
"""
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.
if DATA is None:
# Simulation mode: there is no measured scan to span, so the
# range is a parameter, in Rayleigh ranges.
z_range = cfg.sim_z_range_z0
else:
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
if DATA is None:
# Nothing to interpolate onto, and nothing to compare against.
# The peak-to-valley figures still describe the simulated
# curves, so they are returned with the data half left NaN;
# build_log_text prints that as "-".
elapsed = time.time() - t_start
return dict(
z=z, z_mm=z_mm, OA=OA, CA=CA, CAOA=CAOA,
OA_interp=None, CA_interp=None, CAOA_interp=None,
OA_chi_square=None, CA_chi_square=None, CAOA_chi_square=None,
deltaOAcomp=np.array([np.nan, 1 - np.min(OA)]),
deltaCAcomp=np.array([np.nan, np.max(CA) - np.min(CA)]),
deltaCAOAcomp=np.array([np.nan, np.max(CAOA) - np.min(CAOA)]),
Io=Io, z_0=z_0, tau=tau, kappa=kappa, Tot_err=Tot_err, z_range=z_range,
elapsed=elapsed,
)
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)
# Fraction of the y span left clear above and below the curves in
# Simulation mode. The panels are autoscaled tight, which in Fitting
# mode is what you want -- the scatter's own spread keeps the extremes
# off the frame -- but a lone smooth curve then runs into the top and
# bottom edges.
SIM_Y_PAD = 0.05
def _pad_y_axis(ax, fraction=SIM_Y_PAD):
"""Widens the y limits by `fraction` of the current span at each
end. Applied after the panel is styled, so it pads what is actually
displayed rather than relying on autoscale's own margins, which the
tight autoscale in _style_panel has already switched off."""
lo, hi = ax.get_ylim()
pad = (hi - lo) * fraction
ax.set_ylim(lo - pad, hi + pad)
def make_fit_figure(cfg: ZScanConfig, DATA, results, line_width=1.25):
"""The Open/Closed aperture panels. With DATA (Fitting mode) each
panel shows the measured points and the simulation interpolated
onto them; with DATA None (Simulation mode) it shows the simulated
curves alone, on the simulation's own z axis."""
fig = Figure(figsize=(9, 4.2))
ax1, ax2 = fig.subplots(1, 2)
if DATA is None:
z_mm = results['z_mm']
sim_line, = ax1.plot(z_mm, results['OA'], '-r', linewidth=line_width, label='Simulation')
_style_panel(ax1, 'Open aperture',
legend_handles=[sim_line], legend_labels=['Simulation'])
if cfg.show_CA:
sim_line2, = ax2.plot(z_mm, results['CA'], '-b', linewidth=line_width, label='Simulation')
title2 = 'Closed aperture'
else:
sim_line2, = ax2.plot(z_mm, results['CAOA'], '-b', linewidth=line_width, label='Simulation')
title2 = 'Closed over open aperture'
_style_panel(ax2, title2, right_hand=True,
legend_handles=[sim_line2], legend_labels=['Simulation'])
_pad_y_axis(ax1)
_pad_y_axis(ax2)
return _finish_figure(fig)
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.
"""
simulation_only = DATA is None
lines = []
lines.append(f"{datetime.datetime.now()}: Begin Z-scan program (zscan_gui.py / zscan_core.py).")
lines.append(f"Operation mode: {'Simulation' if simulation_only else 'Fitting'}")
if simulation_only:
lines.append("No data imported; the calculated signals are shown alone.\n")
else:
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}')
if simulation_only:
lines.append(f' z range: {cfg.sim_z_range_z0:6.3f} z_0 (half-width)')
else:
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')
if simulation_only:
# Only the simulated half of each pair exists, and there is
# nothing to compute a chi-square against.
lines.append('DeltaT_PV (simulated):')
lines.append(f" Delta_OA: {results['deltaOAcomp'][1]:6.3f}")
lines.append(f" Delta_CA: {results['deltaCAcomp'][1]:6.3f}")
lines.append(f" Delta_CAOA: {results['deltaCAOAcomp'][1]:6.3f}\n")
else:
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,
export_basepath=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).
With DATA None (Simulation mode) the CSV holds the simulated curves
on the simulation's own z axis, there is no reference figure, and
the output names come from `export_basepath` -- a path chosen by
the caller, since there is no imported file to derive them from.
"""
# 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(export_basepath if export_basepath else 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]
if DATA is None:
export_data = np.column_stack([
results['z_mm'], results['OA'], results['CA'], results['CAOA'],
])
header = 'Position (mm),OA (Simulation),CA (Simulation),OACA (Simulation)'
else:
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)