Upload files to "/"

This commit is contained in:
2026-09-24 01:31:32 +00:00
parent d608ec3d31
commit 752fb79048
3 changed files with 405 additions and 52 deletions
+135 -24
View File
@@ -31,6 +31,8 @@ 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
@@ -65,6 +67,21 @@ def rmmissing(arr):
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 ---
@@ -134,6 +151,10 @@ class ZScanConfig:
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)
@@ -311,7 +332,7 @@ def load_and_normalize_data(cfg: ZScanConfig):
# PHYSICS SIMULATION
# =============================================================================
def run_simulation(cfg: ZScanConfig, DATA: np.ndarray):
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
@@ -349,8 +370,13 @@ def run_simulation(cfg: ZScanConfig, DATA: np.ndarray):
# 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)
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)
@@ -463,6 +489,23 @@ def run_simulation(cfg: ZScanConfig, DATA: np.ndarray):
# 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))
@@ -890,9 +933,49 @@ def make_reference_figure(DATA, norm_OA, norm_CA, do_norm_OA=True, do_norm_CA=Tr
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')
@@ -949,9 +1032,14 @@ def build_log_text(cfg: ZScanConfig, DATA, results, exported_paths=None) -> str:
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"Import data file {cfg.import_filepath}.\n")
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}')
@@ -972,9 +1060,12 @@ def build_log_text(cfg: ZScanConfig, DATA, results, exported_paths=None) -> str:
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)')
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:')
@@ -1015,15 +1106,23 @@ def build_log_text(cfg: ZScanConfig, DATA, results, exported_paths=None) -> str:
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")
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('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} %')
@@ -1041,12 +1140,18 @@ def build_log_text(cfg: ZScanConfig, DATA, results, exported_paths=None) -> str:
return "\n".join(lines)
def export_results(cfg: ZScanConfig, DATA, results, fit_fig, ref_fig=None):
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
@@ -1056,7 +1161,7 @@ def export_results(cfg: ZScanConfig, DATA, results, fit_fig, ref_fig=None):
# 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)
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'
@@ -1076,13 +1181,19 @@ def export_results(cfg: ZScanConfig, DATA, results, fit_fig, ref_fig=None):
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)')
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')