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
+220 -17
View File
@@ -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))