#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ zscan_gui.py ============ Desktop GUI for the Z-scan beam simulation (zscan_core.py). Lets you: * Browse for and select the raw z-scan data file * Edit every simulation/processing parameter in labeled fields * Run the simulation (in a background thread so the window doesn't freeze) and see the two result plots embedded right in the window * Read off the fit-quality numbers (chi-square, delta-T comparisons) * Optionally export the fit/data CSV, a log file, and plot images Requires: numpy, scipy, matplotlib (tkinter ships with most standard Python installs; on some Linux distros install it separately, e.g. `sudo apt install python3-tk`). Run with: python zscan_gui.py """ import os import re import threading import traceback from dataclasses import replace import tkinter as tk import tkinter.font as tkfont from tkinter import ttk, filedialog, messagebox from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from zscan_core import ( ZScanConfig, load_and_normalize_data, peek_column_count, resolve_endpts, run_simulation, refine_fit, make_reference_figure, make_fit_figure, export_results, build_log_text, save_settings, load_settings, apply_tight_layout, DEFAULT_ENDPTS_PERCENT, ) SETTINGS_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "last_settings.json") # Starting width of the left parameter panel, and of the plot pane # beside it -- together these set the default window width. PARAM_PANEL_WIDTH = 358 # panel content asks for 355px at 10pt PLOT_PANE_WIDTH = 800 # + the panel scrollbar, so the window opens ~1173px # Width (in characters) of the unit-label column on rows that carry a # "Refine" checkbox -- wide enough for the longest unit there # ("m^3/W^2", 7 chars) so every checkbox lands at the same x. UNIT_COLUMN_CHARS = 8 # Width of the label column. The default is sized for the longest # label in the panel ("d (focus->aperture)"), which leaves the # Nonlinear Parameters rows -- whose labels are all short, and which # are the widest rows in the panel because they also carry a unit AND # a Refine checkbox -- with ~79px of empty column between label and # entry. Those rows get their own column, sized for "alpha_2". LABEL_COLUMN_CHARS = 16 NONLINEAR_LABEL_CHARS = 8 # ----------------------------------------------------------------------- # Small helper widgets # ----------------------------------------------------------------------- _FLOAT_PARTIAL_RE = re.compile(r'^[+-]?(\d+\.?\d*|\.\d*)?([eE][+-]?\d*)?$') _INT_PARTIAL_RE = re.compile(r'^[+-]?\d*$') # Non-negative variants: no leading sign on the overall number, but the # exponent's own sign (e.g. the "-19" in "5e-19") is still allowed, # since that just makes a small positive number, not a negative one. _FLOAT_PARTIAL_NONNEG_RE = re.compile(r'^(\d+\.?\d*|\.\d*)?([eE][+-]?\d*)?$') _INT_PARTIAL_NONNEG_RE = re.compile(r'^\d*$') class LabeledEntry(ttk.Frame): """A label + entry pair on one row, with typed get()/set(). When kind is int or float, keystrokes that would make the field's text invalid as a (possibly partial, e.g. '-', '1.', '1e-') number are rejected as they're typed, rather than only failing later when get() parses the text. str-kind fields (e.g. delimiter, extra label in the Data File section) are left unrestricted. Pass allow_negative=False to additionally reject a leading minus sign (the exponent's own sign, e.g. the '-19' in '5e-19', is still allowed, since that makes a small positive number). Pass fit_checkbox=True to add a small "Fit" checkbox at the end of the row (see fit_enabled()) -- used by the Nonlinear Parameters fields to mark which ones Refine Fit should optimize.""" def __init__(self, parent, label, value, width=14, kind=float, unit="", allow_negative=True, fit_checkbox=False, label_width=LABEL_COLUMN_CHARS): super().__init__(parent) self.kind = kind self.allow_negative = allow_negative ttk.Label(self, text=label, width=label_width, anchor="w").pack(side="left") self.var = tk.StringVar(value=str(value)) entry = ttk.Entry(self, textvariable=self.var, width=width) if kind in (int, float): vcmd = (self.register(self._validate_numeric_input), "%P") entry.configure(validate="key", validatecommand=vcmd) entry.pack(side="left") self.entry = entry if unit: unit_label = ttk.Label(self, text=unit, foreground="#666") if fit_checkbox: # Fixed-width unit column, so the checkboxes still line # up vertically once they're packed flush against it. unit_label.configure(width=UNIT_COLUMN_CHARS, anchor="w") unit_label.pack(side="left", padx=(4, 0)) if fit_checkbox: self.fit_var = tk.BooleanVar(value=False) # side="left", not "right". Packed right, the checkbox was # pinned to the far edge of the row, and since rows stretch # to the width of the WIDEST row in the panel, that opened a # ragged gap after the unit label on every shorter row. # Packed left it sits flush, and the row's natural width is # all the panel has to provide. ttk.Checkbutton(self, text="Refine", variable=self.fit_var).pack(side="left", padx=(6, 0)) else: self.fit_var = None def fit_enabled(self) -> bool: return self.fit_var is not None and self.fit_var.get() def set_enabled(self, enabled: bool): self.entry.configure(state="normal" if enabled else "disabled") def is_enabled(self) -> bool: return str(self.entry.cget("state")) != "disabled" def is_empty(self) -> bool: return self.var.get().strip() == "" def _validate_numeric_input(self, proposed_text): if proposed_text == "": return True if self.kind is int: pattern = _INT_PARTIAL_RE if self.allow_negative else _INT_PARTIAL_NONNEG_RE else: pattern = _FLOAT_PARTIAL_RE if self.allow_negative else _FLOAT_PARTIAL_NONNEG_RE return bool(pattern.match(proposed_text)) def get(self): return self.kind(self.var.get().strip()) def set(self, value): self.var.set(str(value)) class LabeledCheck(ttk.Frame): def __init__(self, parent, label, value=False, command=None): super().__init__(parent) self.var = tk.BooleanVar(value=bool(value)) cb_kwargs = {"command": command} if command is not None else {} self.checkbutton = ttk.Checkbutton(self, text=label, variable=self.var, **cb_kwargs) self.checkbutton.pack(side="left") def get(self): return self.var.get() def set(self, value): self.var.set(bool(value)) def set_enabled(self, enabled: bool): self.checkbutton.configure(state="normal" if enabled else "disabled") class ResizableFigureCanvas: """ Embeds a Matplotlib Figure inside `holder` and keeps it letterboxed (or pillarboxed) at its original aspect ratio as `holder` is resized -- i.e. the plot grows/shrinks with the window but is never stretched out of proportion. """ def __init__(self, holder, fig): self.holder = holder self.fig = fig self.aspect = fig.get_figwidth() / fig.get_figheight() self.dpi = fig.get_dpi() self.canvas = FigureCanvasTkAgg(fig, master=holder) self.widget = self.canvas.get_tk_widget() self.widget.place(x=0, y=0) holder.bind("", self._resize) holder.update_idletasks() self._resize() def _resize(self, event=None): if event is not None: w, h = event.width, event.height else: w, h = self.holder.winfo_width(), self.holder.winfo_height() if w < 2 or h < 2: return if w / h > self.aspect: new_h = h new_w = int(round(h * self.aspect)) else: new_w = w new_h = int(round(w / self.aspect)) # Enforce a minimum figure width. Below this, the fixed-point- # size text (titles/labels/ticks/legend) genuinely no longer # fits no matter how the layout margins are tuned -- tight_layout # itself gives up in that range. Better to let the plot extend # past a too-small panel (normal, expected UX) than to render # illegibly with text clipped inside it. min_w = int(6.0 * self.dpi) if new_w < min_w: new_w = min_w new_h = int(round(min_w / self.aspect)) x, y = (w - new_w) // 2, (h - new_h) // 2 self.widget.place(x=x, y=y, width=new_w, height=new_h) # Explicitly resize the Figure itself (rather than relying on # the backend's own auto-resize handling) so the plot always # redraws sharp at its new pixel size. self.fig.set_size_inches(new_w / self.dpi, new_h / self.dpi, forward=False) # Re-run the layout at the new size. Axes margins are fixed # FRACTIONS of the figure (set once by tight_layout at creation # time), but text (titles/labels/ticks/legend) is fixed POINT # sizes -- so shrinking the figure to fit a smaller GUI panel # leaves those margins without enough absolute room for the # same text, and it overflows past the figure edge, getting # clipped by the widget's bounds. Recomputing here keeps the # whole figure visible at any panel size. apply_tight_layout(self.fig) self.canvas.draw_idle() def add_section(parent, title): frame = ttk.LabelFrame(parent, text=title, padding=8) frame.pack(fill="x", padx=8, pady=6) return frame # ----------------------------------------------------------------------- # Main application # ----------------------------------------------------------------------- class ZScanApp(tk.Tk): # Preferred font, with metric-compatible / widely-available fallbacks # in case a given Linux install doesn't have Liberation Sans (e.g. a # minimal Fedora spin without the `liberation-fonts` package). PREFERRED_FONT_FAMILIES = ("Liberation Sans", "DejaVu Sans", "Noto Sans", "Arial", "Helvetica") FONT_SIZE = 10 def __init__(self): super().__init__() self.title("Z-Scan Beam Simulation") self.geometry(f"{PARAM_PANEL_WIDTH + PLOT_PANE_WIDTH}x820") self._configure_fonts() self.DATA = None self.norm_OA = None self.norm_CA = None self.results = None self.fit_fig = None self.ref_fig = None self.cfg = None self._data_col_count = None self._has_imported = False self._build_layout() self._load_previous_settings() self._on_use_freq_toggle() self._on_use_ref_toggle() def _configure_fonts(self): """Set every stock Tk/ttk font to 10pt Liberation Sans (falling back to another common sans-serif family if Liberation Sans isn't installed on this system) so all widgets -- including ones that don't take an explicit font= argument -- pick it up consistently. Note on anti-aliasing: Tk has no separate on/off flag for this. Anti-aliased rendering is handled by the OS's font engine (Xft/fontconfig on Linux/X11, DirectWrite on Windows, Core Text on macOS) whenever a scalable TrueType/OpenType family is used, which is the default on any modern Tk 8.6+ build. On Linux this is controlled by fontconfig / your desktop environment's font settings, not by this script. """ # Tk/X11 font-family names are frequently reported in lowercase # (e.g. "liberation sans" rather than "Liberation Sans"), so # match case-insensitively but keep the exact string Tk itself # reports when actually configuring the font. available = {f.lower(): f for f in tkfont.families(self)} chosen = None for preferred in self.PREFERRED_FONT_FAMILIES: if preferred.lower() in available: chosen = available[preferred.lower()] break if chosen is None: chosen = "TkDefaultFont" print(f"[zscan_gui] Warning: none of {self.PREFERRED_FONT_FAMILIES} were found " f"via Tk's font list; falling back to the system default font.") elif chosen.lower() != self.PREFERRED_FONT_FAMILIES[0].lower(): print(f"[zscan_gui] Note: '{self.PREFERRED_FONT_FAMILIES[0]}' not found; " f"using '{chosen}' instead. (On Fedora: sudo dnf install liberation-fonts)") self.ui_font = (chosen, self.FONT_SIZE) for name in ("TkDefaultFont", "TkTextFont", "TkFixedFont", "TkMenuFont", "TkHeadingFont", "TkCaptionFont", "TkSmallCaptionFont", "TkIconFont", "TkTooltipFont"): try: tkfont.nametofont(name).configure(family=chosen, size=self.FONT_SIZE) except tk.TclError: pass self.option_add("*Font", self.ui_font) style = ttk.Style(self) style.configure(".", font=self.ui_font) # ------------------------------------------------------------------ # Layout # ------------------------------------------------------------------ def _build_layout(self): outer = ttk.PanedWindow(self, orient="horizontal") outer.pack(fill="both", expand=True) # Both panes are added up front so the left/right order of the # PanedWindow doesn't depend on the order their contents are # built in -- the right pane's action bar has to be built # FIRST, because _build_param_fields ends by attaching traces # that call _update_run_button_state, which needs self.run_button # to already exist. # NOTE: the width has to go on the CANVAS, not on left_container. # A Frame sizes itself to its packed children, so ttk.Frame(..., # width=N) here is silently ignored -- the old width=380 never # took effect at all, and the panel just inherited tk.Canvas's # 394px default. That default was narrow enough to cut the # "Refine" checkboxes off the right-hand end of the Nonlinear # Parameters rows until the user dragged the sash wider. # PARAM_PANEL_WIDTH is the visible viewport; the scrollbar sits # outside it, so the pane ends up ~15px wider still. The sash # remains user-draggable -- this only sets where it starts. left_container = ttk.Frame(outer) outer.add(left_container, weight=0) right = ttk.Frame(outer) outer.add(right, weight=1) # --- right: action bar + notebook of plots + log --- self._build_action_bar(right) self.notebook = ttk.Notebook(right) self.notebook.pack(fill="both", expand=True, padx=6, pady=(6, 0)) self.tab_ref = ttk.Frame(self.notebook) self.tab_fit = ttk.Frame(self.notebook) self.tab_log = ttk.Frame(self.notebook) self.notebook.add(self.tab_ref, text="Referenced / Normalized") self.notebook.add(self.tab_fit, text="Fit Results") self.notebook.add(self.tab_log, text="Fit Quality / Log") self.log_text = tk.Text(self.tab_log, wrap="word", font=self.ui_font) self.log_text.pack(fill="both", expand=True, padx=6, pady=6) self.ref_canvas_holder = ttk.Frame(self.tab_ref) self.ref_canvas_holder.pack(fill="both", expand=True) self.fit_canvas_holder = ttk.Frame(self.tab_fit) self.fit_canvas_holder.pack(fill="both", expand=True) # --- bottom status bar --- status_bar = ttk.Frame(right) status_bar.pack(fill="x", padx=6, pady=6) self.status_var = tk.StringVar(value="Ready.") ttk.Label(status_bar, textvariable=self.status_var).pack(side="left") self.progress = ttk.Progressbar(status_bar, mode="indeterminate", length=160) self.progress.pack(side="right") # --- left: scrollable parameter panel --- canvas = tk.Canvas(left_container, borderwidth=0, highlightthickness=0, width=PARAM_PANEL_WIDTH) scrollbar = ttk.Scrollbar(left_container, orient="vertical", command=canvas.yview) self.param_frame = ttk.Frame(canvas) self.param_frame.bind( "", lambda _event: canvas.configure(scrollregion=canvas.bbox("all")) ) canvas.create_window((0, 0), window=self.param_frame, anchor="nw") canvas.configure(yscrollcommand=scrollbar.set) canvas.pack(side="left", fill="both", expand=True) scrollbar.pack(side="right", fill="y") self.param_canvas = canvas self._build_param_fields(self.param_frame) def _build_action_bar(self, parent): """The five action buttons, in one row directly above the plot pane, left to right in the order they're used: Import -> Run Simulation -> Refine Fit -> Export, then Exit. Laid out with grid rather than pack so `uniform` can hold all five columns to the same width regardless of label length, and so they keep that width as the pane is resized. Every button carries the SAME 3px padding on both sides and the outer 3px is put on the frame instead. Padding the two end buttons asymmetrically (0 outside, 3 inside) would leave them 3px wider than the rest, since uniform equalizes the columns, not the widgets inside them. 3 + 3 also lines the row's outer edges up with the notebook's own 6px padx below it. """ bar = ttk.Frame(parent) bar.pack(fill="x", padx=3, pady=(6, 0)) self.import_button = ttk.Button(bar, text="Import", command=self._on_import) self.run_button = ttk.Button(bar, text="Run Simulation", command=self._on_run, state="disabled") self.refine_button = ttk.Button(bar, text="Refine Fit", command=self._on_refine_fit, state="disabled") self.export_button = ttk.Button(bar, text="Export...", command=self._on_export, state="disabled") self.exit_button = ttk.Button(bar, text="Exit", command=self._on_exit) # Exit is in the uniform group with the other four, so all five # are the same width and share the same 3px padding. It is the # one button here that ends the session rather than advancing # the workflow, so it is placed last, furthest from Import. buttons = (self.import_button, self.run_button, self.refine_button, self.export_button, self.exit_button) for column, button in enumerate(buttons): button.grid(row=0, column=column, sticky="ew", padx=3) bar.columnconfigure(column, weight=1, uniform="action_buttons") def _build_param_fields(self, parent): # --- File --- sec = add_section(parent, "Data File") self.filepath_var = tk.StringVar(value="") row = ttk.Frame(sec) row.pack(fill="x", pady=2) ttk.Entry(row, textvariable=self.filepath_var, width=28).pack(side="left", fill="x", expand=True) ttk.Button(row, text="Browse...", command=self._browse_file).pack(side="left", padx=(4, 0)) self.delimiter = LabeledEntry(sec, "Delimiter", "", width=10, kind=str, unit='(blank = auto)') self.delimiter.pack(fill="x", pady=2) self.extra_label = LabeledEntry(sec, "Extra label", "", width=14, kind=str) self.extra_label.pack(fill="x", pady=2) sec = add_section(parent, "Data Columns (1-indexed)") self.z_col = LabeledEntry(sec, "z column", 1, kind=int, allow_negative=False) self.CA_col = LabeledEntry(sec, "CA column", 2, kind=int, allow_negative=False) self.OA_col = LabeledEntry(sec, "OA column", 5, kind=int, allow_negative=False) self.REF_col = LabeledEntry(sec, "REF column", 8, kind=int, allow_negative=False) self.FREQ_col = LabeledEntry(sec, "FREQ column", 4, kind=int, allow_negative=False) for w in (self.z_col, self.CA_col, self.OA_col, self.REF_col, self.FREQ_col): w.pack(fill="x", pady=2) sec = add_section(parent, "Processing Flags") self.use_ref = LabeledCheck(sec, "Use reference channel", True, command=self._on_use_ref_toggle) self.use_freq = LabeledCheck(sec, "Use frequency channel", False, command=self._on_use_freq_toggle) self.flip_z = LabeledCheck(sec, "flip_z (flip z-axis)", True) self.do_norm_OA = LabeledCheck(sec, "Normalize OA (slope fit)", True) self.do_norm_CA = LabeledCheck(sec, "Normalize CA (slope fit)", True) self.flip_OA = LabeledCheck(sec, "flip_OA", False) self.flip_CA = LabeledCheck(sec, "flip_CA", False) self.flip_REF = LabeledCheck(sec, "flip_REF", False) self.flip_OA_disp = LabeledCheck(sec, "flip_OA_disp", False) self.flip_CA_disp = LabeledCheck(sec, "flip_CA_disp", False) self.show_CA = LabeledCheck(sec, "Show CA (else OA/CA)", True) for w in (self.use_ref, self.use_freq, self.flip_z, self.do_norm_OA, self.do_norm_CA, self.flip_OA, self.flip_CA, self.flip_REF, self.flip_OA_disp, self.flip_CA_disp, self.show_CA): w.pack(fill="x", pady=1) sec = add_section(parent, "Nonlinear Parameters") self.n_2 = LabeledEntry(sec, "n_2", 10e-19, unit="m^2/W", fit_checkbox=True, label_width=NONLINEAR_LABEL_CHARS) self.n_3 = LabeledEntry(sec, "n_3", 0, unit="m^4/W^2", fit_checkbox=True, label_width=NONLINEAR_LABEL_CHARS) self.n_4 = LabeledEntry(sec, "n_4", 0, unit="m^6/W^3", fit_checkbox=True, label_width=NONLINEAR_LABEL_CHARS) self.alpha_2 = LabeledEntry(sec, "alpha_2", 0, unit="m/W", fit_checkbox=True, label_width=NONLINEAR_LABEL_CHARS) self.alpha_3 = LabeledEntry(sec, "alpha_3", 0, unit="m^3/W^2", fit_checkbox=True, label_width=NONLINEAR_LABEL_CHARS) self.alpha_4 = LabeledEntry(sec, "alpha_4", 2.2e-43, unit="m^5/W^3", fit_checkbox=True, label_width=NONLINEAR_LABEL_CHARS) for w in (self.n_2, self.n_3, self.n_4, self.alpha_2, self.alpha_3, self.alpha_4): w.pack(fill="x", pady=2) sec = add_section(parent, "z-Position Offsets [mm]") self.Delta_z_OA = LabeledEntry(sec, "Delta_z_OA", 0.05) self.Delta_z_CA = LabeledEntry(sec, "Delta_z_CA", 0.23) self.Delta_z_OACA = LabeledEntry(sec, "Delta_z_OACA", 0.0) for w in (self.Delta_z_OA, self.Delta_z_CA, self.Delta_z_OACA): w.pack(fill="x", pady=2) sec = add_section(parent, "Sample Parameters") self.n = LabeledEntry(sec, "n (linear)", 3.0337, allow_negative=False) self.L = LabeledEntry(sec, "L", 0.188, unit="mm", allow_negative=False) self.T_lin = LabeledEntry(sec, "T_lin", 1.0, allow_negative=False) for w in (self.n, self.L, self.T_lin): w.pack(fill="x", pady=2) sec = add_section(parent, "Laser Parameters") self.E = LabeledEntry(sec, "E (pulse energy)", 180, unit="nJ", allow_negative=False) self.lambda_ = LabeledEntry(sec, "lambda", 2000, unit="nm", allow_negative=False) self.w_0 = LabeledEntry(sec, "w_0 (waist)", 19, unit="um", allow_negative=False) self.tau_FWHM = LabeledEntry(sec, "tau_FWHM", 50, unit="fs", allow_negative=False) self.M2 = LabeledEntry(sec, "M^2", 1.0, allow_negative=False) for w in (self.E, self.lambda_, self.w_0, self.tau_FWHM, self.M2): w.pack(fill="x", pady=2) sec = add_section(parent, "Measurement Parameters") self.S = LabeledEntry(sec, "S (aperture trans.)", 0.33, allow_negative=False) self.d = LabeledEntry(sec, "d (focus->aperture)", 100, unit="cm", allow_negative=False) for w in (self.S, self.d): w.pack(fill="x", pady=2) sec = add_section(parent, "Error Estimates (fraction)") self.E_err = LabeledEntry(sec, "E_err", 0.10, allow_negative=False) self.w_err = LabeledEntry(sec, "w_err", 0.10, allow_negative=False) self.tau_err = LabeledEntry(sec, "tau_err", 0.10, allow_negative=False) for w in (self.E_err, self.w_err, self.tau_err): w.pack(fill="x", pady=2) sec = add_section(parent, "Simulation Parameters") self.z_points = LabeledEntry(sec, "z_points (even)", 76, kind=int, allow_negative=False) self.r_points = LabeledEntry(sec, "r_points", 500, kind=int, allow_negative=False) self.r_max = LabeledEntry(sec, "r_max", 3, unit="w", allow_negative=False) self.t_points = LabeledEntry(sec, "t_points", 50, kind=int, allow_negative=False) self.t_max = LabeledEntry(sec, "t_max", 3, unit="tau", allow_negative=False) self.ra_points = LabeledEntry(sec, "ra_points", 50, kind=int, allow_negative=False) # "% per side" measures 67px, exactly the space left over before # the Nonlinear rows stop being the panel's widest -- so the # unit is spelled out at no cost to the panel width. self.endpts_percent = LabeledEntry(sec, "endpts", DEFAULT_ENDPTS_PERCENT, kind=float, allow_negative=False, unit="% per side") self.max_iterations = LabeledEntry(sec, "Max iterations", 100, kind=int, allow_negative=False) for w in (self.z_points, self.r_points, self.r_max, self.t_points, self.t_max, self.ra_points, self.endpts_percent, self.max_iterations): w.pack(fill="x", pady=2) ttk.Label( sec, text="Memory ~ r_points x ra_points x t_points x z_points x 16 bytes.\n" "Large grids (defaults) can use several GB of RAM.", foreground="#a33", wraplength=PARAM_PANEL_WIDTH - 60, justify="left", ).pack(fill="x", pady=(4, 0)) # The Import / Run / Refine / Export / Exit buttons live in the # action bar above the plot pane (_build_action_bar), not here. # Every numeric input field outside the Data File section -- # Run Simulation stays disabled if any of these is left empty. self._required_entry_fields = [ self.z_col, self.CA_col, self.OA_col, self.REF_col, self.FREQ_col, self.n_2, self.n_3, self.n_4, self.alpha_2, self.alpha_3, self.alpha_4, self.Delta_z_OA, self.Delta_z_CA, self.Delta_z_OACA, self.n, self.L, self.T_lin, self.E, self.lambda_, self.w_0, self.tau_FWHM, self.M2, self.S, self.d, self.E_err, self.w_err, self.tau_err, self.z_points, self.r_points, self.r_max, self.t_points, self.t_max, self.ra_points, self.endpts_percent, ] for field_widget in self._required_entry_fields: field_widget.var.trace_add("write", lambda *_args: self._update_run_button_state()) # Data Columns + Processing Flags -- once Import has been used # at least once, changing any of these live-refreshes the # Referenced/Normalized plot without needing to click Import # again. show_CA is deliberately absent: it selects which series # the FIT figure's right-hand panel shows and never reaches # make_reference_figure, so refreshing on it just re-read the # data file and redrew an identical plot. self._reference_refresh_fields = [ self.z_col, self.CA_col, self.OA_col, self.REF_col, self.FREQ_col, self.use_ref, self.use_freq, self.flip_z, self.do_norm_OA, self.do_norm_CA, self.flip_OA, self.flip_CA, self.flip_REF, self.flip_OA_disp, self.flip_CA_disp, self.endpts_percent, ] for field_widget in self._reference_refresh_fields: field_widget.var.trace_add("write", lambda *_args: self._refresh_reference_plot()) def _on_use_freq_toggle(self): """Enables/disables the FREQ column field based on the 'Use frequency channel' checkbox -- the FREQ column's data isn't actually used in any calculation, so this only controls whether the field is editable, not any computation. When the imported file has exactly 4 columns, use_ref and use_freq are mutually exclusive (only one may be checked at a time), since there's only one "extra" column beyond z/CA/OA for either a reference or a frequency channel to occupy.""" if self._data_col_count == 4 and self.use_freq.get() and self.use_ref.get(): self.use_ref.set(False) self.REF_col.set_enabled(False) self.FREQ_col.set_enabled(self.use_freq.get()) def _on_use_ref_toggle(self): """Enables/disables the REF column field based on the 'Use reference channel' checkbox. See _on_use_freq_toggle for the 4-column mutual-exclusion behavior.""" if self._data_col_count == 4 and self.use_ref.get() and self.use_freq.get(): self.use_freq.set(False) self.FREQ_col.set_enabled(False) self.REF_col.set_enabled(self.use_ref.get()) def _apply_column_count_constraint(self, n_cols): """Constrains use_ref/use_freq based on how many columns the imported file actually has: - 3 columns (just z, CA, OA): neither flag can be used -- forced off and disabled. - 4 columns: only one of the two may be enabled at a time (see the mutual exclusion in the toggle handlers above). - 5+ columns: no restriction, both may be enabled. """ self._data_col_count = n_cols if n_cols <= 3: self.use_ref.set(False) self.use_freq.set(False) self.use_ref.set_enabled(False) self.use_freq.set_enabled(False) elif n_cols == 4: self.use_ref.set_enabled(True) self.use_freq.set_enabled(True) if self.use_ref.get() and self.use_freq.get(): self.use_freq.set(False) else: self.use_ref.set_enabled(True) self.use_freq.set_enabled(True) self._on_use_ref_toggle() self._on_use_freq_toggle() # ------------------------------------------------------------------ # Actions # ------------------------------------------------------------------ def _browse_file(self): path = filedialog.askopenfilename( title="Select z-scan data file", filetypes=[("Text/data files", "*.txt *.dat *.csv"), ("All files", "*.*")], ) if path: self.filepath_var.set(path) def _gather_config(self) -> ZScanConfig: return ZScanConfig( import_filepath=self.filepath_var.get(), delimiter=self.delimiter.get(), extra_label=self.extra_label.get(), z_col=self.z_col.get(), CA_col=self.CA_col.get(), OA_col=self.OA_col.get(), REF_col=self.REF_col.get(), FREQ_col=self.FREQ_col.get(), use_ref=self.use_ref.get(), use_freq=self.use_freq.get(), flip_z=int(self.flip_z.get()), do_norm_OA=self.do_norm_OA.get(), do_norm_CA=self.do_norm_CA.get(), flip_OA=int(self.flip_OA.get()), flip_CA=int(self.flip_CA.get()), flip_REF=int(self.flip_REF.get()), flip_OA_disp=int(self.flip_OA_disp.get()), flip_CA_disp=int(self.flip_CA_disp.get()), show_CA=self.show_CA.get(), n_2=self.n_2.get(), n_3=self.n_3.get(), n_4=self.n_4.get(), alpha_2=self.alpha_2.get(), alpha_3=self.alpha_3.get(), alpha_4=self.alpha_4.get(), Delta_z_OA=self.Delta_z_OA.get(), Delta_z_CA=self.Delta_z_CA.get(), Delta_z_OACA=self.Delta_z_OACA.get(), n=self.n.get(), L=self._clean_float(self.L.get() * 1e-3), T_lin=self.T_lin.get(), E=self._clean_float(self.E.get() * 1e-9), lambda_=self._clean_float(self.lambda_.get() * 1e-9), w_0=self._clean_float(self.w_0.get() * 1e-6), tau_FWHM=self._clean_float(self.tau_FWHM.get() * 1e-15), M2=self.M2.get(), S=self.S.get(), d=self._clean_float(self.d.get() * 1e-2), E_err=self.E_err.get(), w_err=self.w_err.get(), tau_err=self.tau_err.get(), z_points=self.z_points.get(), r_points=self.r_points.get(), r_max=self.r_max.get(), t_points=self.t_points.get(), t_max=self.t_max.get(), ra_points=self.ra_points.get(), endpts_percent=self.endpts_percent.get(), max_iterations=self.max_iterations.get(), ) @staticmethod def _clean_float(value, sig_figs=12): """Rounds away floating-point round-trip noise from the unit-conversion multiply/divide pairs (e.g. 19 um -> 1.9e-05 m -> back to um can land on 18.999999999999996 instead of 19) while preserving all real precision a user could plausibly have typed. 12 significant figures is well beyond any practical input precision but comfortably below float64's 15-17 digit noise floor.""" return float(f"{value:.{sig_figs}g}") def _apply_config_to_fields(self, cfg: ZScanConfig): """Populates every field widget from a loaded ZScanConfig -- the exact inverse of _gather_config, including reversing the display-unit conversions (E/lambda/w_0/tau_FWHM/L/d).""" self.filepath_var.set(cfg.import_filepath) self.delimiter.set(cfg.delimiter) self.extra_label.set(cfg.extra_label) self.z_col.set(cfg.z_col) self.CA_col.set(cfg.CA_col) self.OA_col.set(cfg.OA_col) self.REF_col.set(cfg.REF_col) self.FREQ_col.set(cfg.FREQ_col) self.use_ref.set(cfg.use_ref) self.use_freq.set(cfg.use_freq) self.flip_z.set(cfg.flip_z) self.do_norm_OA.set(cfg.do_norm_OA) self.do_norm_CA.set(cfg.do_norm_CA) self.flip_OA.set(cfg.flip_OA) self.flip_CA.set(cfg.flip_CA) self.flip_REF.set(cfg.flip_REF) self.flip_OA_disp.set(cfg.flip_OA_disp) self.flip_CA_disp.set(cfg.flip_CA_disp) self.show_CA.set(cfg.show_CA) self.n_2.set(cfg.n_2) self.n_3.set(cfg.n_3) self.n_4.set(cfg.n_4) self.alpha_2.set(cfg.alpha_2) self.alpha_3.set(cfg.alpha_3) self.alpha_4.set(cfg.alpha_4) self.Delta_z_OA.set(cfg.Delta_z_OA) self.Delta_z_CA.set(cfg.Delta_z_CA) self.Delta_z_OACA.set(cfg.Delta_z_OACA) self.n.set(cfg.n) self.L.set(self._clean_float(cfg.L * 1e3)) self.T_lin.set(cfg.T_lin) self.E.set(self._clean_float(cfg.E * 1e9)) self.lambda_.set(self._clean_float(cfg.lambda_ * 1e9)) self.w_0.set(self._clean_float(cfg.w_0 * 1e6)) self.tau_FWHM.set(self._clean_float(cfg.tau_FWHM * 1e15)) self.M2.set(cfg.M2) self.S.set(cfg.S) self.d.set(self._clean_float(cfg.d * 1e2)) self.E_err.set(cfg.E_err) self.w_err.set(cfg.w_err) self.tau_err.set(cfg.tau_err) self.z_points.set(cfg.z_points) self.r_points.set(cfg.r_points) self.r_max.set(cfg.r_max) self.t_points.set(cfg.t_points) self.t_max.set(cfg.t_max) self.ra_points.set(cfg.ra_points) self.endpts_percent.set(cfg.endpts_percent) self.max_iterations.set(cfg.max_iterations) def _load_previous_settings(self): """Loads last_settings.json (saved on the previous exit) and restores every field from it. If the file doesn't exist, is corrupt, or otherwise can't be loaded, this silently leaves every field at the hardcoded defaults they were already built with -- no error shown, since a missing/bad settings file on first run (or after a manual delete) is entirely normal.""" if not os.path.isfile(SETTINGS_PATH): return try: cfg = load_settings(SETTINGS_PATH) self._apply_config_to_fields(cfg) print(f"zscan_gui: previous settings loaded from {SETTINGS_PATH}.") except Exception as exc: print(f"zscan_gui: could not load {SETTINGS_PATH} ({exc}); using defaults.") def _on_exit(self): try: save_settings(self._gather_config(), SETTINGS_PATH) except Exception as exc: print(f"zscan_gui: failed to save settings to {SETTINGS_PATH}: {exc}") self.destroy() def _on_import(self): """Loads and normalizes the data file and immediately shows it in the Referenced/Normalized tab, using the exact same figure (make_reference_figure) that "Run Simulation" populates that tab with -- so the two look identical, just available sooner, before running the full (potentially slow) simulation.""" try: cfg = self._gather_config() except Exception as exc: messagebox.showerror("Invalid parameter", str(exc)) return if not cfg.import_filepath or not os.path.isfile(cfg.import_filepath): messagebox.showerror("File not found", "Please select a valid data file.") return try: n_cols = peek_column_count(cfg.import_filepath, cfg.delimiter) except Exception: tb = traceback.format_exc() messagebox.showerror("Import failed", tb.strip().splitlines()[-1]) return # Constrain use_ref/use_freq to what the file's actual column # count allows *before* the full load, since a stale flag # pointing past a smaller file's columns would otherwise fail # with an out-of-bounds index. self._apply_column_count_constraint(n_cols) cfg = self._gather_config() try: DATA = self._load_reference(cfg) except Exception: tb = traceback.format_exc() messagebox.showerror("Import failed", tb.strip().splitlines()[-1]) return self.notebook.select(self.tab_ref) # The percentage is reported alongside the count it resolved to, # since the count depends on this file's number of points. self.status_var.set( f"Imported {DATA.shape[0]} points ({n_cols} columns) from " f"{os.path.basename(cfg.import_filepath)}; " f"endpts = {cfg.endpts_percent:g}% " f"({resolve_endpts(cfg.endpts_percent, DATA.shape[0])} points per side)." ) self._has_imported = True self._update_run_button_state() def _load_reference(self, cfg: ZScanConfig): """Load cfg's data file and show it in the Referenced/Normalized tab, keeping self.DATA / self.norm_* / self.cfg / self.ref_fig in step. Shared by Import and the live refresh, which previously each did this inline -- and both left self.ref_fig pointing at whatever figure the last Run had built, so exporting after changing a column or a processing flag wrote out a reference image that no longer matched the plot on screen.""" DATA, norm_OA, norm_CA = load_and_normalize_data(cfg) self.DATA, self.norm_OA, self.norm_CA, self.cfg = DATA, norm_OA, norm_CA, cfg self.ref_fig = make_reference_figure(DATA, norm_OA, norm_CA, cfg.do_norm_OA, cfg.do_norm_CA) self._embed_figure(self.ref_canvas_holder, self.ref_fig) return DATA def _update_run_button_state(self): """Run Simulation stays disabled until a file has been successfully imported AND every required field (everything outside the Data File section) has a non-empty value. Fields currently disabled (e.g. REF column while 'Use reference channel' is unchecked) are skipped, since their value doesn't matter to the simulation while they're inactive.""" if not self._has_imported: self.run_button.config(state="disabled") return if any(w.is_enabled() and w.is_empty() for w in self._required_entry_fields): self.run_button.config(state="disabled") return self.run_button.config(state="normal") def _refresh_reference_plot(self): """Re-loads the data file and redraws the Referenced/Normalized plot with the current Data Columns / Processing Flags settings. Only takes effect after Import has been used at least once; before that, or if the current settings are momentarily invalid (e.g. mid-edit of a column number, or a column index the file doesn't have), this silently does nothing and leaves whatever was last successfully shown in place.""" if not self._has_imported: return try: cfg = self._gather_config() except Exception: return if not cfg.import_filepath or not os.path.isfile(cfg.import_filepath): return try: self._load_reference(cfg) except Exception: return def _on_run(self): try: cfg = self._gather_config() except Exception as exc: messagebox.showerror("Invalid parameter", str(exc)) return if not cfg.import_filepath or not os.path.isfile(cfg.import_filepath): messagebox.showerror("File not found", "Please select a valid data file.") return if cfg.z_points % 2 != 0: if not messagebox.askyesno("z_points is odd", "z_points should normally be even. Continue anyway?"): return self.run_button.config(state="disabled") self.refine_button.config(state="disabled") self.export_button.config(state="disabled") self.status_var.set("Running simulation...") self.progress.start(12) self.log_text.delete("1.0", "end") thread = threading.Thread(target=self._run_worker, args=(cfg,), daemon=True) thread.start() def _run_worker(self, cfg: ZScanConfig): try: DATA, norm_OA, norm_CA = load_and_normalize_data(cfg) results = run_simulation(cfg, DATA) ref_fig = make_reference_figure(DATA, norm_OA, norm_CA, cfg.do_norm_OA, cfg.do_norm_CA) fit_fig = make_fit_figure(cfg, DATA, results) self.DATA, self.norm_OA, self.norm_CA = DATA, norm_OA, norm_CA self.results, self.fit_fig, self.ref_fig, self.cfg = results, fit_fig, ref_fig, cfg self.after(0, self._on_run_success) except Exception: tb = traceback.format_exc() self.after(0, self._on_run_error, tb) def _on_run_success(self): # Reads the results off self rather than taking them as # arguments: the worker has already stored every one of them # there, so passing the same objects through as well was two # copies of the same handoff. Only ever one run is in flight -- # Run is disabled for the duration. self._embed_figure(self.ref_canvas_holder, self.ref_fig) self._embed_figure(self.fit_canvas_holder, self.fit_fig) self.log_text.delete("1.0", "end") self.log_text.insert("1.0", build_log_text(self.cfg, self.DATA, self.results)) self.progress.stop() self.status_var.set("Done.") self._update_run_button_state() self.refine_button.config(state="normal") self.export_button.config(state="normal") self.notebook.select(self.tab_fit) def _on_run_error(self, tb_text): self.progress.stop() self.status_var.set("Error.") self._update_run_button_state() self.refine_button.config(state="disabled") self.export_button.config(state="disabled") self.log_text.delete("1.0", "end") self.log_text.insert("1.0", tb_text) self.notebook.select(self.tab_log) messagebox.showerror("Simulation failed", tb_text.strip().splitlines()[-1]) def _on_refine_fit(self): """Runs a downhill-simplex (Nelder-Mead) search over whichever nonlinear parameters have their 'Refine' checkbox ticked, to minimize the RMSE between the simulated fit and the actual data -- requires a prior successful Run Simulation, since it refines starting from that result's data and parameters.""" if self.results is None or self.DATA is None or self.cfg is None: messagebox.showerror("Nothing to refine", "Run the simulation first.") return param_names = [name for name in ("n_2", "n_3", "n_4", "alpha_2", "alpha_3", "alpha_4") if getattr(self, name).fit_enabled()] if not param_names: messagebox.showerror( "No parameters selected", "Check the 'Refine' box next to at least one nonlinear parameter to refine.", ) return try: cfg = self._gather_config() except Exception as exc: messagebox.showerror("Invalid parameter", str(exc)) return self.run_button.config(state="disabled") self.refine_button.config(state="disabled") self.export_button.config(state="disabled") self.status_var.set(f"Refining fit ({', '.join(param_names)})...") self.progress.start(12) thread = threading.Thread( target=self._refine_fit_worker, args=(cfg, param_names, cfg.max_iterations), daemon=True ) thread.start() def _refine_fit_worker(self, cfg: ZScanConfig, param_names, max_iter): def progress_callback(iteration, rmse): self.after(0, self.status_var.set, f"Refining fit... iteration {iteration}, RMSE={rmse:.4g}") try: best_cfg, best_results, opt_result = refine_fit( cfg, self.DATA, param_names, max_iter=max_iter, progress_callback=progress_callback, ) # Round only the just-optimized parameters to 6 significant # figures (Nelder-Mead's raw output has far more precision # than is physically meaningful), then re-run the simulation # at those rounded values so the displayed fields, plots and # log all stay consistent with each other -- rather than # showing a rounded number next to a plot/log still # reflecting the optimizer's full-precision internal result. # Done here in the worker, not in the _on_refine_success # callback: that callback runs on the Tk main thread, where # a full extra run_simulation froze the window for as long # as a single simulation takes. rounded_kwargs = {name: self._clean_float(getattr(best_cfg, name), sig_figs=6) for name in param_names} best_cfg = replace(best_cfg, **rounded_kwargs) self.after(0, self.status_var.set, "Re-running at rounded parameter values...") best_results = run_simulation(best_cfg, self.DATA) self.after(0, self._on_refine_success, best_cfg, best_results, opt_result, param_names) except Exception: tb = traceback.format_exc() self.after(0, self._on_refine_error, tb) def _on_refine_success(self, best_cfg: ZScanConfig, best_results, opt_result, param_names): # best_cfg/best_results already come in rounded and re-run -- # see _refine_fit_worker. for name in param_names: getattr(self, name).set(getattr(best_cfg, name)) # Only the nonlinear parameters changed, and the reference # figure is built from the data and the normalization flags -- # none of which refining touches. Rebuilding it here produced an # identical figure. fit_fig = make_fit_figure(best_cfg, self.DATA, best_results) self._embed_figure(self.fit_canvas_holder, fit_fig) self.results, self.fit_fig, self.cfg = best_results, fit_fig, best_cfg self.log_text.delete("1.0", "end") self.log_text.insert("1.0", build_log_text(best_cfg, self.DATA, best_results)) self.progress.stop() state_word = "converged" if opt_result.success else "stopped (did not fully converge)" self.status_var.set( f"Refine Fit {state_word} after {opt_result.nit} iterations, RMSE={opt_result.fun:.4g}." ) self._update_run_button_state() self.refine_button.config(state="normal") self.export_button.config(state="normal") self.notebook.select(self.tab_fit) def _on_refine_error(self, tb_text): self.progress.stop() self.status_var.set("Refine Fit failed.") self._update_run_button_state() self.refine_button.config(state="normal") self.export_button.config(state="normal") self.log_text.delete("1.0", "end") self.log_text.insert("1.0", tb_text) self.notebook.select(self.tab_log) messagebox.showerror("Refine Fit failed", tb_text.strip().splitlines()[-1]) def _on_export(self): if self.results is None: return try: export_paths = export_results(self.cfg, self.DATA, self.results, self.fit_fig, self.ref_fig) except Exception: tb = traceback.format_exc() messagebox.showerror("Export failed", tb.strip().splitlines()[-1]) return self.status_var.set("Export complete.") # Regenerated from build_log_text with the export paths, rather # than appending an "Exported files:" block to whatever is # currently on screen -- appending stacked a fresh duplicate # block on every repeat export, and formatted it differently # from the identical listing inside the exported _log.txt. self.log_text.delete("1.0", "end") self.log_text.insert("1.0", build_log_text(self.cfg, self.DATA, self.results, export_paths)) self.notebook.select(self.tab_log) messagebox.showinfo("Export complete", "Exported:\n" + "\n".join(export_paths)) def _embed_figure(self, holder, fig): for child in holder.winfo_children(): child.destroy() view = ResizableFigureCanvas(holder, fig) # Keep a strong reference alive (Tkinter/Matplotlib won't hold # one for us, and a garbage-collected canvas stops redrawing). if holder is self.ref_canvas_holder: self._ref_view = view else: self._fit_view = view if __name__ == "__main__": app = ZScanApp() app.protocol("WM_DELETE_WINDOW", app._on_exit) app.mainloop()