Upload files to "/"
This commit is contained in:
@@ -23,6 +23,9 @@ FM4I.6](https://doi.org/10.1364/FIO.2012.FM4I.6)) — see
|
||||
|
||||
## Features
|
||||
|
||||
- **Two operation modes.** *Fitting* imports a measured scan and compares the
|
||||
simulation with it. *Simulation* calculates and displays the signals with no
|
||||
data at all, over a z range you specify.
|
||||
- **Load raw scan files** with configurable 1-indexed column mapping, so data
|
||||
from different acquisition setups can be read without editing the file. A
|
||||
header row is skipped. Leaving the delimiter blank splits on whitespace,
|
||||
@@ -90,30 +93,58 @@ python zscan_gui.py
|
||||
|
||||
## Usage
|
||||
|
||||
1. **Browse** to a scan file and set the column numbers for position, CA, OA and
|
||||
1. **Choose the Operation Mode** — *Fitting* (the default) or *Simulation*.
|
||||
The steps below describe Fitting; for Simulation see
|
||||
[Simulation mode](#simulation-mode).
|
||||
2. **Browse** to a scan file and set the column numbers for position, CA, OA and
|
||||
the reference channel. Columns are 1-indexed, matching how they are usually
|
||||
numbered in acquisition software.
|
||||
2. **Import.** The Referenced / Normalized tab shows the raw and corrected
|
||||
3. **Import.** The Referenced / Normalized tab shows the raw and corrected
|
||||
traces with the baseline fit drawn over them, so you can confirm the columns
|
||||
and flags are right before simulating. Changing a column or a processing flag
|
||||
re-reads the file and redraws immediately.
|
||||
3. **Enter the measurement parameters** — pulse energy, wavelength, beam waist,
|
||||
4. **Enter the measurement parameters** — pulse energy, wavelength, beam waist,
|
||||
pulse width, sample thickness and refractive index, aperture transmittance.
|
||||
4. **Run Simulation** to overlay the simulated curves on the data.
|
||||
5. **Refine Fit** — tick the coefficients to vary and let the optimizer adjust
|
||||
5. **Run Simulation** to overlay the simulated curves on the data.
|
||||
6. **Refine Fit** — tick the coefficients to vary and let the optimizer adjust
|
||||
them. It runs in the background with a live iteration count.
|
||||
6. **Export** to write the fit data, log and images next to the input file.
|
||||
7. **Export** to write the fit data, log and images next to the input file.
|
||||
|
||||
### Simulation mode
|
||||
|
||||
Selecting **Simulation** calculates the signals without any measurement. Every
|
||||
input that describes a data file is switched off — the Data File, Data Columns
|
||||
and Processing Flags boxes, along with **Import**, **Refine Fit**, **Max
|
||||
iterations** and the Referenced / Normalized tab — and **Run Simulation**
|
||||
becomes available with nothing imported.
|
||||
|
||||
The scan's extent is not measured but stated: **z range (sim.)** sets the
|
||||
half-width in Rayleigh ranges *z₀* either side of focus (default 15). The
|
||||
Fit Results panels show the simulated curves alone, padded by 5% above and
|
||||
below, and the log reports the simulated peak-to-valley values in place of the
|
||||
data-versus-fit comparison and chi-squares.
|
||||
|
||||
**Show CA (else OA/CA)** stays available, since it selects which curve the
|
||||
right-hand panel draws and both are simulated. Ticking it repeats the run so
|
||||
the plot follows immediately.
|
||||
|
||||
Anything already imported is kept while you work in Simulation, so switching
|
||||
back to Fitting does not mean importing again. Switching either way clears the
|
||||
results on screen, which belonged to the other mode.
|
||||
|
||||
### Exported files
|
||||
|
||||
Written alongside the input file, with an optional extra label in the name:
|
||||
Written alongside the input file, with an optional extra label in the name. In
|
||||
Simulation mode there is no input file to name them from, so **Export** asks
|
||||
where to write; the CSV then holds the simulated curves and no reference figure
|
||||
is produced:
|
||||
|
||||
| File | Contents |
|
||||
|---|---|
|
||||
| `<name>_fit.<ext>` | CSV of position, data and fit for the OA, CA and CA/OA curves |
|
||||
| `<name>_fit.<ext>` | CSV of position, data and fit for the OA, CA and CA/OA curves; in Simulation, position and the simulated OA, CA and CA/OA |
|
||||
| `<name>_fit_log.txt` | Every parameter, fit-quality metric and output path |
|
||||
| `<name>_fit.jpg` / `.svg` | Fit figure, raster and vector |
|
||||
| `<name>_fit_ref.jpg` / `.svg` | Referenced/normalized figure |
|
||||
| `<name>_fit_ref.jpg` / `.svg` | Referenced/normalized figure (Fitting only) |
|
||||
|
||||
## Project structure
|
||||
|
||||
@@ -141,6 +172,13 @@ The program is split so the physics can be used without the interface:
|
||||
|
||||
## Parameters
|
||||
|
||||
### Operation mode
|
||||
|
||||
| Option | Effect |
|
||||
|--------------|-----------------------------------------------------------------|
|
||||
| `Fitting` | Default. Imports a scan and compares the simulation with it. |
|
||||
| `Simulation` | No data: the calculated signals are shown alone, over `z range (sim.)`. The data-file inputs, Import, Refine Fit, Max iterations and the Referenced / Normalized tab are disabled. |
|
||||
|
||||
### Data columns (1-indexed)
|
||||
|
||||
| Variable | Default | Column contents |
|
||||
@@ -218,14 +256,15 @@ uncertainty
|
||||
|
||||
| Parameter | Default | Meaning |
|
||||
|-------------|---------|-----------------------------------------------------|
|
||||
| `z_points` | `75` | Number of z-scan points (must be even) |
|
||||
| `z_points` | `76` | Number of z-scan points (must be even) |
|
||||
| `r_points` | `500` | Radial points at the sample |
|
||||
| `r_max` | `3` | Radial integration limit, in beam radii *w* |
|
||||
| `t_points` | `50` | Temporal points |
|
||||
| `t_max` | `3` | Temporal integration limit, in pulse widths *τ* |
|
||||
| `ra_points` | `50` | Radial points at the closed aperture |
|
||||
| `endpts_%` | `10` | Percentage of edge points to use for normalization |
|
||||
| `max_iter` | `100` | Maximum iterations for the parameter refinement |
|
||||
| `z range (sim.)` | `15` | Half-width of the simulated scan, in Rayleigh ranges *z₀*. Simulation mode only |
|
||||
| `max_iter` | `100` | Maximum iterations for the parameter refinement (Fitting only) |
|
||||
|
||||
Memory use scales as `r_points x ra_points x t_points x z_points`, so raising
|
||||
the grid resolution raises RAM sharply; the interface shows the estimate as you
|
||||
|
||||
+135
-24
@@ -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')
|
||||
|
||||
|
||||
+220
-17
@@ -63,9 +63,19 @@ from zscan_core import (
|
||||
save_settings,
|
||||
load_settings,
|
||||
apply_tight_layout,
|
||||
OPERATION_FITTING,
|
||||
OPERATION_SIMULATION,
|
||||
DEFAULT_SIM_Z_RANGE_Z0,
|
||||
DEFAULT_ENDPTS_PERCENT,
|
||||
)
|
||||
|
||||
# The "Operation Mode" box's toggle, in display order: (mode, label).
|
||||
OPERATION_CHOICES = [
|
||||
(OPERATION_FITTING, "Fitting"),
|
||||
(OPERATION_SIMULATION, "Simulation"),
|
||||
]
|
||||
OPERATION_LABELS = dict(OPERATION_CHOICES)
|
||||
|
||||
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
|
||||
@@ -195,6 +205,11 @@ class LabeledCheck(ttk.Frame):
|
||||
def set_enabled(self, enabled: bool):
|
||||
self.checkbutton.configure(state="normal" if enabled else "disabled")
|
||||
|
||||
def is_enabled(self) -> bool:
|
||||
# Mirrors LabeledEntry, so callers can treat either the same
|
||||
# way when enabling or disabling a whole box of inputs.
|
||||
return str(self.checkbutton.cget("state")) != "disabled"
|
||||
|
||||
|
||||
class ResizableFigureCanvas:
|
||||
"""
|
||||
@@ -463,13 +478,28 @@ class ZScanApp(tk.Tk):
|
||||
bar.columnconfigure(column, weight=1, uniform="action_buttons")
|
||||
|
||||
def _build_param_fields(self, parent):
|
||||
sec = add_section(parent, "Operation Mode")
|
||||
self._configure_mode_toggle_style()
|
||||
self.operation_mode_var = tk.StringVar(value=OPERATION_FITTING)
|
||||
self._mode_buttons = []
|
||||
width = max(len(label) for _, label in OPERATION_CHOICES)
|
||||
for mode, label in OPERATION_CHOICES:
|
||||
b = ttk.Radiobutton(sec, text=label, value=mode,
|
||||
variable=self.operation_mode_var,
|
||||
command=self._on_operation_mode_change,
|
||||
style="Mode.Toolbutton", width=width)
|
||||
b.pack(side="left") # abutting, so the pair reads as one control
|
||||
self._mode_buttons.append(b)
|
||||
|
||||
# --- 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.filepath_entry = ttk.Entry(row, textvariable=self.filepath_var, width=28)
|
||||
self.filepath_entry.pack(side="left", fill="x", expand=True)
|
||||
self.browse_button = ttk.Button(row, text="Browse...", command=self._browse_file)
|
||||
self.browse_button.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)
|
||||
@@ -496,11 +526,25 @@ class ZScanApp(tk.Tk):
|
||||
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)
|
||||
self.show_CA = LabeledCheck(sec, "Show CA (else OA/CA)", True,
|
||||
command=self._on_show_CA_toggle)
|
||||
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)
|
||||
|
||||
# The inputs Simulation mode switches off: everything that
|
||||
# describes a measured file, which that mode has none of.
|
||||
# "Show CA (else OA/CA)" is deliberately not among them --
|
||||
# it picks which curve the right-hand panel draws, and both are
|
||||
# simulated, so it still does something with no data loaded.
|
||||
self._data_widgets = [
|
||||
self.delimiter, self.extra_label,
|
||||
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,
|
||||
]
|
||||
|
||||
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)
|
||||
@@ -565,9 +609,13 @@ class ZScanApp(tk.Tk):
|
||||
# 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")
|
||||
# Simulation mode only: with no data, the scan's extent has to
|
||||
# be stated rather than measured.
|
||||
self.sim_z_range_z0 = LabeledEntry(sec, "z range (sim.)", DEFAULT_SIM_Z_RANGE_Z0,
|
||||
kind=float, allow_negative=False, unit="+/- z_0")
|
||||
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):
|
||||
self.endpts_percent, self.sim_z_range_z0, self.max_iterations):
|
||||
w.pack(fill="x", pady=2)
|
||||
ttk.Label(
|
||||
sec,
|
||||
@@ -699,6 +747,8 @@ class ZScanApp(tk.Tk):
|
||||
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(),
|
||||
operation_mode=self.operation_mode_var.get(),
|
||||
sim_z_range_z0=self.sim_z_range_z0.get(),
|
||||
max_iterations=self.max_iterations.get(),
|
||||
)
|
||||
|
||||
@@ -765,6 +815,9 @@ class ZScanApp(tk.Tk):
|
||||
self.t_max.set(cfg.t_max)
|
||||
self.ra_points.set(cfg.ra_points)
|
||||
self.endpts_percent.set(cfg.endpts_percent)
|
||||
self.sim_z_range_z0.set(cfg.sim_z_range_z0)
|
||||
self.operation_mode_var.set(cfg.operation_mode)
|
||||
self._apply_operation_mode_to_widgets()
|
||||
self.max_iterations.set(cfg.max_iterations)
|
||||
|
||||
def _load_previous_settings(self):
|
||||
@@ -854,6 +907,115 @@ class ZScanApp(tk.Tk):
|
||||
self._embed_figure(self.ref_canvas_holder, self.ref_fig)
|
||||
return DATA
|
||||
|
||||
# Selection colour of Tk's "default" theme (its radio-button
|
||||
# indicator), so the toggle matches the rest of the panel.
|
||||
MODE_SELECTED_BG = "#4a6984"
|
||||
|
||||
def _configure_mode_toggle_style(self):
|
||||
"""The Operation Mode box's two radio buttons drawn as a
|
||||
segmented toggle: a pair of equal-width buttons, the selected
|
||||
one filled.
|
||||
|
||||
Built on ttk's Toolbutton, but with a border on both states: in
|
||||
the "default" theme a plain Toolbutton draws one only on the
|
||||
selected option, leaving the other looking like a bare label
|
||||
rather than something to click. Colours are explicit, so the
|
||||
toggle looks the same under any ttk theme. Map entries are
|
||||
tried in order, so the disabled ones -- the buttons are locked
|
||||
while a run is in flight -- come first."""
|
||||
style = ttk.Style(self)
|
||||
style.configure("Mode.Toolbutton", padding=(12, 3), anchor="center",
|
||||
relief="raised", borderwidth=1, background="#e8e8e6")
|
||||
style.map("Mode.Toolbutton",
|
||||
relief=[("selected", "sunken")],
|
||||
background=[("disabled", "selected", "#9aa8b5"),
|
||||
("selected", self.MODE_SELECTED_BG),
|
||||
("disabled", "#e8e8e6"),
|
||||
("active", "#f4f4f2")],
|
||||
foreground=[("disabled", "selected", "#eef1f4"),
|
||||
("disabled", "#a3a3a3"),
|
||||
("selected", "white")])
|
||||
|
||||
def _apply_operation_mode_to_widgets(self):
|
||||
"""Makes the panel, the buttons and the tabs reflect the
|
||||
selected mode. Simulation has no measured scan, so everything
|
||||
that describes one is switched off: the Data File, Data Columns
|
||||
and Processing Flags inputs, Import, Refine Fit, and the
|
||||
Referenced / Normalized tab. The simulated z range is the
|
||||
mirror image -- meaningful only in Simulation."""
|
||||
simulation = self.operation_mode_var.get() == OPERATION_SIMULATION
|
||||
for w in self._data_widgets:
|
||||
w.set_enabled(not simulation)
|
||||
self.filepath_entry.state(["disabled"] if simulation else ["!disabled"])
|
||||
self.browse_button.state(["disabled"] if simulation else ["!disabled"])
|
||||
self.sim_z_range_z0.set_enabled(simulation)
|
||||
# Refine Fit's iteration cap, and Refine Fit is unavailable
|
||||
# without data, so the field has nothing to govern here.
|
||||
self.max_iterations.set_enabled(not simulation)
|
||||
|
||||
self.import_button.config(state="disabled" if simulation else "normal")
|
||||
if simulation:
|
||||
self.refine_button.config(state="disabled")
|
||||
|
||||
# A disabled tab cannot be the selected one.
|
||||
if simulation and self.notebook.select() == str(self.tab_ref):
|
||||
self.notebook.select(self.tab_fit)
|
||||
self.notebook.tab(self.tab_ref, state="disabled" if simulation else "normal")
|
||||
|
||||
# 'Use reference/frequency channel' also gate REF/FREQ column,
|
||||
# but only while the boxes they live in are active at all.
|
||||
if not simulation:
|
||||
self._on_use_ref_toggle()
|
||||
self._on_use_freq_toggle()
|
||||
self._update_run_button_state()
|
||||
|
||||
def _on_show_CA_toggle(self):
|
||||
"""Show CA picks which curve the right-hand panel draws, and
|
||||
that curve is chosen while the figure is built -- so the plot
|
||||
on screen only follows the tick once the run is repeated. Does
|
||||
it straight away, rather than leaving the panel disagreeing
|
||||
with the box until the next manual run.
|
||||
|
||||
Skipped when there is nothing on screen to bring up to date, or
|
||||
when a run is already under way (the button is disabled then),
|
||||
so the tick is free to be set before the first run.
|
||||
"""
|
||||
if self.results is None:
|
||||
return
|
||||
if str(self.run_button.cget("state")) != "normal":
|
||||
return
|
||||
self._on_run()
|
||||
|
||||
def _on_operation_mode_change(self):
|
||||
self._set_operation_mode(self.operation_mode_var.get())
|
||||
|
||||
def _set_operation_mode(self, mode):
|
||||
"""Switches mode and clears any results on screen: they were
|
||||
produced by the other mode, over a different z range and
|
||||
against different inputs, so they no longer describe what the
|
||||
panel says. Imported data is kept, so returning to Fitting does
|
||||
not mean importing again."""
|
||||
self.operation_mode_var.set(mode)
|
||||
|
||||
self.results = self.fit_fig = None
|
||||
for holder in (self.fit_canvas_holder,):
|
||||
for child in holder.winfo_children():
|
||||
child.destroy()
|
||||
self._fit_view = None
|
||||
self.log_text.delete("1.0", "end")
|
||||
self.export_button.config(state="disabled")
|
||||
self.refine_button.config(state="disabled")
|
||||
|
||||
self._apply_operation_mode_to_widgets()
|
||||
# Settings are written on exit, as for every other field here.
|
||||
self.status_var.set(f"Operation mode: {OPERATION_LABELS[mode]}.")
|
||||
|
||||
def _set_mode_buttons_enabled(self, enabled: bool):
|
||||
"""The run happens on a worker thread that reads the config
|
||||
throughout, so the mode must not change underneath it."""
|
||||
for b in self._mode_buttons:
|
||||
b.state(["!disabled"] if enabled else ["disabled"])
|
||||
|
||||
def _update_run_button_state(self):
|
||||
"""Run Simulation stays disabled until a file has been
|
||||
successfully imported AND every required field (everything
|
||||
@@ -861,7 +1023,7 @@ class ZScanApp(tk.Tk):
|
||||
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:
|
||||
if self.operation_mode_var.get() == OPERATION_FITTING and 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):
|
||||
@@ -897,7 +1059,8 @@ class ZScanApp(tk.Tk):
|
||||
messagebox.showerror("Invalid parameter", str(exc))
|
||||
return
|
||||
|
||||
if not cfg.import_filepath or not os.path.isfile(cfg.import_filepath):
|
||||
simulation = cfg.operation_mode == OPERATION_SIMULATION
|
||||
if not simulation and (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:
|
||||
@@ -908,6 +1071,7 @@ class ZScanApp(tk.Tk):
|
||||
self.run_button.config(state="disabled")
|
||||
self.refine_button.config(state="disabled")
|
||||
self.export_button.config(state="disabled")
|
||||
self._set_mode_buttons_enabled(False)
|
||||
self.status_var.set("Running simulation...")
|
||||
self.progress.start(12)
|
||||
self.log_text.delete("1.0", "end")
|
||||
@@ -917,13 +1081,23 @@ class ZScanApp(tk.Tk):
|
||||
|
||||
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)
|
||||
if cfg.operation_mode == OPERATION_SIMULATION:
|
||||
# No file is read at all, and there is no
|
||||
# Referenced/Normalized figure to build. Anything
|
||||
# already imported is left alone, so switching back to
|
||||
# Fitting does not mean importing again.
|
||||
results = run_simulation(cfg, None)
|
||||
fit_fig = make_fit_figure(cfg, None, results)
|
||||
self.results, self.fit_fig, self.cfg = results, fit_fig, cfg
|
||||
else:
|
||||
DATA, norm_OA, norm_CA = load_and_normalize_data(cfg)
|
||||
ref_fig = make_reference_figure(DATA, norm_OA, norm_CA,
|
||||
cfg.do_norm_OA, cfg.do_norm_CA)
|
||||
results = run_simulation(cfg, DATA)
|
||||
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.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:
|
||||
@@ -931,26 +1105,31 @@ class ZScanApp(tk.Tk):
|
||||
self.after(0, self._on_run_error, tb)
|
||||
|
||||
def _on_run_success(self):
|
||||
simulation = self.cfg.operation_mode == OPERATION_SIMULATION
|
||||
# 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)
|
||||
if not simulation:
|
||||
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.log_text.insert("1.0", build_log_text(self.cfg, self._results_data(), self.results))
|
||||
|
||||
self.progress.stop()
|
||||
self.status_var.set("Done.")
|
||||
self._set_mode_buttons_enabled(True)
|
||||
self._update_run_button_state()
|
||||
self.refine_button.config(state="normal")
|
||||
# Nothing to refine against without data.
|
||||
self.refine_button.config(state="disabled" if simulation else "normal")
|
||||
self.export_button.config(state="normal")
|
||||
self.notebook.select(self.tab_fit)
|
||||
|
||||
def _on_run_error(self, tb_text):
|
||||
self.progress.stop()
|
||||
self._set_mode_buttons_enabled(True)
|
||||
self.status_var.set("Error.")
|
||||
self._update_run_button_state()
|
||||
self.refine_button.config(state="disabled")
|
||||
@@ -1066,11 +1245,34 @@ class ZScanApp(tk.Tk):
|
||||
self.notebook.select(self.tab_log)
|
||||
messagebox.showerror("Refine Fit failed", tb_text.strip().splitlines()[-1])
|
||||
|
||||
def _results_data(self):
|
||||
"""The data the current results describe: None after a
|
||||
simulation, whatever was imported after a fit. self.DATA can
|
||||
hold an imported scan even in Simulation mode, since running a
|
||||
simulation no longer discards it."""
|
||||
if self.cfg is not None and self.cfg.operation_mode == OPERATION_SIMULATION:
|
||||
return None
|
||||
return self.DATA
|
||||
|
||||
def _on_export(self):
|
||||
if self.results is None:
|
||||
return
|
||||
export_basepath = None
|
||||
if self.cfg.operation_mode == OPERATION_SIMULATION:
|
||||
# No imported file to take the output names from, so ask
|
||||
# where to put them. The chosen name is the base: the usual
|
||||
# _fit / _fit_log / .jpg / .svg names are built from it.
|
||||
export_basepath = filedialog.asksaveasfilename(
|
||||
title="Export simulation as",
|
||||
defaultextension=".txt",
|
||||
filetypes=[("Text files", "*.txt"), ("All files", "*.*")])
|
||||
if not export_basepath:
|
||||
return
|
||||
try:
|
||||
export_paths = export_results(self.cfg, self.DATA, self.results, self.fit_fig, self.ref_fig)
|
||||
export_paths = export_results(self.cfg, self._results_data(), self.results,
|
||||
self.fit_fig,
|
||||
None if export_basepath else self.ref_fig,
|
||||
export_basepath=export_basepath)
|
||||
except Exception:
|
||||
tb = traceback.format_exc()
|
||||
messagebox.showerror("Export failed", tb.strip().splitlines()[-1])
|
||||
@@ -1083,7 +1285,8 @@ class ZScanApp(tk.Tk):
|
||||
# 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.log_text.insert("1.0",
|
||||
build_log_text(self.cfg, self._results_data(), self.results, export_paths))
|
||||
self.notebook.select(self.tab_log)
|
||||
messagebox.showinfo("Export complete", "Exported:\n" + "\n".join(export_paths))
|
||||
|
||||
|
||||
Reference in New Issue
Block a user