1992 lines
89 KiB
Python
1992 lines
89 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
# BD Fresnel - desktop interface
|
|
#
|
|
# Copyright (C) 2019-2026 Manuel R. Ferdinandus
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify
|
|
# it under the terms of the GNU General Public License as published by
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU General Public License
|
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
"""
|
|
bd_fresnel_gui.py
|
|
==================
|
|
|
|
Desktop GUI for the beam-deflection Fresnel-propagation fitting
|
|
program (bd_fresnel_core.py). Tkinter port of BD_Fresnel_GUI.m /
|
|
BD_Fresnel_GUI.fig.
|
|
|
|
Lets you:
|
|
* Enter pump/probe beam and material parameters
|
|
* Select up to 7 simultaneous physical "mechanisms" and set each
|
|
one's parameters via the set_params_dialog popup
|
|
* Import a transmission/deflection data file
|
|
* Run the simulation ("Fit" -- in the original app, and here, this
|
|
means "forward-simulate with the current parameters over the
|
|
delay range spanned by the imported data," not an automated
|
|
least-squares optimizer; you compare the simulated curve to the
|
|
data by eye and adjust parameters, exactly as in the original)
|
|
* See live Transmission (%) and DeltaE/E (%) vs. delay plots
|
|
* Export the fit/data comparison as CSV plus a detailed log file
|
|
* Settings persist between sessions (JSON file next to this script,
|
|
replacing the original's last_settings.mat)
|
|
|
|
Run with: python bd_fresnel_gui.py
|
|
"""
|
|
|
|
import os
|
|
import time
|
|
import threading
|
|
import traceback
|
|
import datetime
|
|
|
|
import numpy as np
|
|
import tkinter as tk
|
|
import tkinter.font as tkfont
|
|
from tkinter import ttk, filedialog, messagebox
|
|
|
|
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
|
|
|
|
from bd_fresnel_core import (
|
|
BDFresnelParams,
|
|
Mechanism,
|
|
MECHANISM_NAMES,
|
|
calc_beam_params,
|
|
inputs_valid,
|
|
BD_Fresnel_func_ni,
|
|
save_settings,
|
|
load_settings,
|
|
MODE_BEAM_DEFLECTION,
|
|
MODE_PUMP_PROBE,
|
|
mechanism_names_for_mode,
|
|
set_mode,
|
|
)
|
|
from set_params_dialog import open_set_params_dialog
|
|
|
|
SETTINGS_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "last_settings.json")
|
|
|
|
# Fields that (in the original MATLAB app) trigger a recompute of the
|
|
# derived beam parameters (calc_beam_params) when edited. Note `l`,
|
|
# `d`, `shift`, `x_0` are deliberately excluded -- see the NOTE 3 in
|
|
# bd_fresnel_core.calc_beam_params for why (faithfully preserved from
|
|
# the original, not a translation gap).
|
|
CALC_BEAM_PARAMS_FIELDS = {
|
|
"E_p", "tau_p_FWHM", "w_0p", "lambda_p",
|
|
"tau_FWHM", "w_0", "lambda_",
|
|
"R_p", "R", "alpha", "alpha_p", "n", "dndl", "n_p", "dndl_p", "alpha_2d",
|
|
}
|
|
|
|
# (field, label, unit, abs_on_entry, log_name) -- mirrors each
|
|
# et_<field>_Callback in BD_Fresnel_GUI.m. abs_on_entry=True means the
|
|
# original applies abs() to the typed value (matching fields whose
|
|
# validation message says "greater than 0" AND which are physically
|
|
# positive-only quantities); the rest accept signed values (even where
|
|
# the log message says ">0", since the original's own numeric
|
|
# validation there is permissive -- only NaN is actually rejected at
|
|
# entry, faithfully preserved).
|
|
PUMP_FIELDS = [
|
|
("E_p", "E_p (pump energy)", "uJ", True),
|
|
("tau_p_FWHM", "tau_p_FWHM", "fs", True),
|
|
("w_0p", "w_0p (pump waist)", "um", True),
|
|
("lambda_p", "lambda_p (pump)", "nm", True),
|
|
]
|
|
PROBE_FIELDS = [
|
|
("tau_FWHM", "tau_FWHM", "fs", True),
|
|
("w_0", "w_0 (probe waist)", "um", True),
|
|
("lambda_", "lambda (probe)", "nm", True),
|
|
]
|
|
MAT_PUMP_FIELDS = [
|
|
("R_p", "R_p (reflectivity)", "0-1", True),
|
|
("alpha_p", "alpha_p (absorption)", "cm^-1", True),
|
|
("n_p", "n_p (index)", "", True),
|
|
("dndl_p", "dndl_p (dispersion)", "um^-1", False),
|
|
("alpha_2d", "alpha_2d (2PA)", "e-11 m/W", False),
|
|
]
|
|
MAT_PROBE_FIELDS = [
|
|
("R", "R (reflectivity)", "0-1", True),
|
|
("alpha", "alpha (absorption)", "cm^-1", True),
|
|
("n", "n (index)", "", True),
|
|
("dndl", "dndl (dispersion)", "um^-1", False),
|
|
]
|
|
SYSTEM_FIELDS = [
|
|
("l", "l (thickness)", "mm", True),
|
|
("d", "d (sample->detector)", "cm", True),
|
|
("shift", "shift (delay zero)", "fs", False),
|
|
("x_0", "x_0 (pump-probe offset)", "w_0p", False),
|
|
]
|
|
|
|
# Escape sequences accepted in the Delimiter field. A literal tab
|
|
# cannot be typed into an Entry (Tab moves focus), so "\t" stands in
|
|
# for one; a blank field means "any run of whitespace", which is what
|
|
# genfromtxt does when given None.
|
|
DELIMITER_ESCAPES = {"\\t": "\t", "\\s": " "}
|
|
|
|
|
|
def resolve_delimiter(text: str):
|
|
"""Turns the Delimiter field's text into the value genfromtxt wants."""
|
|
if not text:
|
|
return None # split on any whitespace
|
|
return DELIMITER_ESCAPES.get(text, text)
|
|
|
|
|
|
def describe_delimiter(text: str) -> str:
|
|
"""Readable name for the delimiter, for the log and console."""
|
|
if not text:
|
|
return "any whitespace"
|
|
return {",": "comma", "\t": "tab", " ": "space", ";": "semicolon",
|
|
"|": "pipe"}.get(resolve_delimiter(text), f"{text!r}")
|
|
|
|
|
|
# The simulation grid, in the order shown in the "Simulation
|
|
# parameters" box: (attribute, label, unit, kind). Integer fields are
|
|
# counts and must be >= 1; the float fields are extents and cannot be
|
|
# negative. T_d_min/T_d_max are deliberately absent -- they are taken
|
|
# from the imported scan's delay range, not entered.
|
|
SIM_FIELDS = [
|
|
("X_num", "X_num (spatial pts)", "points", "int"),
|
|
("X_max", "X_max (spatial extent)", "w_0", "float"),
|
|
("T_num", "T_num (time pts)", "points", "int"),
|
|
("T_max", "T_max (time extent)", "tau_p", "float"),
|
|
("T_d_num", "T_d_num (delay pts)", "points", "int"),
|
|
]
|
|
|
|
# The numeric parameter boxes, in panel order. Each entry is
|
|
# (section title, field list); the field tuples are
|
|
# (attribute, label, unit, restrict-to-nonnegative).
|
|
NUMERIC_FIELD_SECTIONS = [
|
|
("Pump (Excitation) Beam", PUMP_FIELDS),
|
|
("Probe Beam", PROBE_FIELDS),
|
|
("Material @ Pump Wavelength", MAT_PUMP_FIELDS),
|
|
("Material @ Probe Wavelength", MAT_PROBE_FIELDS),
|
|
("System Geometry", SYSTEM_FIELDS),
|
|
]
|
|
|
|
# attribute -> restrict-to-nonnegative, flattened once at import rather
|
|
# than rebuilt on every field edit.
|
|
FIELD_IS_NONNEGATIVE = {
|
|
name: nonneg
|
|
for _, fields in NUMERIC_FIELD_SECTIONS
|
|
for name, _label, _unit, nonneg in fields
|
|
}
|
|
FIELD_IS_NONNEGATIVE.update(
|
|
{name: True for name, _l, _u, kind in SIM_FIELDS if kind == "float"})
|
|
|
|
class ColumnConflict(ValueError):
|
|
"""Two quantities are set to read from the same data column. Kept
|
|
distinct from other read errors because it is a normal intermediate
|
|
state while swapping two column numbers, one field at a time."""
|
|
|
|
|
|
# The "Mode" box's radio buttons, in display order: (mode, label). The
|
|
# labels are also what the parameter log records.
|
|
MODE_CHOICES = [
|
|
(MODE_BEAM_DEFLECTION, "Beam deflection"),
|
|
(MODE_PUMP_PROBE, "Pump probe"),
|
|
]
|
|
MODE_LABELS = dict(MODE_CHOICES)
|
|
|
|
# Which column of the imported file feeds each quantity. 1-based, in
|
|
# the order they are shown in the "Data columns" box.
|
|
DATA_COLUMN_FIELDS = [
|
|
("col_tau_d", "tau_d column"),
|
|
("col_T", "T column"),
|
|
("col_DeltaEoE", "DeltaEoE column"),
|
|
]
|
|
|
|
|
|
# -----------------------------------------------------------------------
|
|
# Small helper widgets
|
|
# -----------------------------------------------------------------------
|
|
|
|
class LabeledEntry(ttk.Frame):
|
|
def __init__(self, parent, label, value, width=12, unit="", on_change=None,
|
|
integer=False, nonnegative=False):
|
|
super().__init__(parent)
|
|
ttk.Label(self, text=label, width=20, anchor="w").pack(side="left")
|
|
self.var = tk.StringVar(value=str(value))
|
|
entry = ttk.Entry(self, textvariable=self.var, width=width)
|
|
entry.pack(side="left")
|
|
self.entry = entry
|
|
if integer:
|
|
# Refuse anything but digits at the keystroke level, so a
|
|
# sign, decimal point or letter can never be typed in the
|
|
# first place. The empty string has to stay allowed or the
|
|
# field could never be cleared to retype it; the value is
|
|
# range-checked (>= 1) when editing finishes.
|
|
entry.configure(validate="key",
|
|
validatecommand=(self.register(self._digits_only), "%P"))
|
|
elif nonnegative:
|
|
entry.configure(validate="key",
|
|
validatecommand=(self.register(self._no_negative_sign), "%P"))
|
|
if unit:
|
|
ttk.Label(self, text=unit, foreground="#666", width=9, anchor="w").pack(side="left", padx=(4, 0))
|
|
if on_change is not None:
|
|
entry.bind("<FocusOut>", lambda e: on_change())
|
|
entry.bind("<Return>", lambda e: on_change())
|
|
|
|
@staticmethod
|
|
def _digits_only(proposed: str) -> bool:
|
|
# str.isdigit() accepts non-ASCII digits and superscripts, which
|
|
# int() then rejects, so test the ASCII digits explicitly.
|
|
return proposed == "" or all(c in "0123456789" for c in proposed)
|
|
|
|
@staticmethod
|
|
def _no_negative_sign(proposed: str) -> bool:
|
|
"""Blocks a minus that would make the value negative, while
|
|
still allowing the one inside an exponent -- otherwise a
|
|
perfectly good entry like 1e-5 could not be typed."""
|
|
return not any(c == "-" and not (i > 0 and proposed[i - 1] in "eE")
|
|
for i, c in enumerate(proposed))
|
|
|
|
def get(self) -> float:
|
|
return float(self.var.get())
|
|
|
|
def get_str(self) -> str:
|
|
"""Raw text, for fields that are not numbers."""
|
|
return self.var.get()
|
|
|
|
def get_int(self) -> int:
|
|
"""Parses a strictly positive integer, raising ValueError on
|
|
anything else (including a blank field or a value of 0)."""
|
|
value = int(self.var.get())
|
|
if value < 1:
|
|
raise ValueError("column numbers start at 1")
|
|
return value
|
|
|
|
def set(self, value):
|
|
self.var.set(str(value))
|
|
|
|
def set_enabled(self, enabled: bool):
|
|
"""Greys the field out and blocks editing, while still showing
|
|
its value."""
|
|
self.entry.state(["!disabled"] if enabled else ["disabled"])
|
|
|
|
|
|
class LabeledStatic(ttk.Frame):
|
|
"""Read-only calculated-value display (e.g. rho, I_0_p)."""
|
|
|
|
def __init__(self, parent, label):
|
|
super().__init__(parent)
|
|
ttk.Label(self, text=label, width=20, anchor="w").pack(side="left")
|
|
self.var = tk.StringVar(value="--")
|
|
ttk.Label(self, textvariable=self.var, width=16, anchor="w",
|
|
foreground="black").pack(side="left")
|
|
|
|
def set(self, value):
|
|
self.var.set(value)
|
|
|
|
|
|
class MechanismRow(ttk.Frame):
|
|
def __init__(self, parent, index, on_change):
|
|
super().__init__(parent)
|
|
self.index = index
|
|
self.on_change = on_change
|
|
ttk.Label(self, text=f"Mech {index + 1}:", width=9, anchor="w").pack(side="left")
|
|
self.mech_var = tk.StringVar(value=MECHANISM_NAMES[0])
|
|
combo = ttk.Combobox(self, textvariable=self.mech_var, values=MECHANISM_NAMES,
|
|
state="readonly", width=26)
|
|
combo.pack(side="left", padx=(0, 4))
|
|
combo.bind("<<ComboboxSelected>>", self._on_selected)
|
|
self.combo = combo
|
|
ttk.Button(self, text="Params...", width=9, command=self._on_params_button).pack(side="left")
|
|
|
|
def _on_selected(self, event=None):
|
|
self.on_change(self.index, self.mech_var.get(), reopen_dialog=True)
|
|
|
|
def _on_params_button(self):
|
|
self.on_change(self.index, self.mech_var.get(), reopen_dialog=True)
|
|
|
|
def set_name(self, name):
|
|
self.mech_var.set(name)
|
|
|
|
def set_choices(self, names):
|
|
"""Replaces the pull-down's list of selectable mechanisms."""
|
|
self.combo.configure(values=names)
|
|
|
|
|
|
def add_section(parent, title):
|
|
frame = ttk.LabelFrame(parent, text=title, padding=8)
|
|
frame.pack(fill="x", padx=8, pady=6)
|
|
return frame
|
|
|
|
|
|
class ResizableFigureCanvas:
|
|
"""Keeps an embedded Matplotlib Figure letterboxed at its original
|
|
aspect ratio as its holder frame is resized (see zscan_gui.py for
|
|
the same pattern / rationale)."""
|
|
|
|
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("<Configure>", 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))
|
|
new_w, new_h = max(new_w, 10), max(new_h, 10)
|
|
|
|
x, y = (w - new_w) // 2, (h - new_h) // 2
|
|
self.widget.place(x=x, y=y, width=new_w, height=new_h)
|
|
|
|
self.fig.set_size_inches(new_w / self.dpi, new_h / self.dpi, forward=False)
|
|
# The holder's own size, which the letterboxed figure may not
|
|
# fill. Pump probe's single panel sizes its text from this
|
|
# rather than from itself -- see _build_combined_figure.
|
|
self.fig._bd_holder_in = (w / self.dpi, h / self.dpi)
|
|
relayout = getattr(self.fig, "_bd_relayout", None)
|
|
if relayout is not None:
|
|
relayout()
|
|
self.canvas.draw_idle()
|
|
|
|
|
|
# -----------------------------------------------------------------------
|
|
# Main application
|
|
# -----------------------------------------------------------------------
|
|
|
|
class BDFresnelApp(tk.Tk):
|
|
PREFERRED_FONT_FAMILIES = ("Liberation Sans", "DejaVu Sans", "Noto Sans", "Arial", "Helvetica")
|
|
FONT_SIZE = 10
|
|
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.title("Beam Deflection Fresnel Fit")
|
|
self.geometry("1300x860")
|
|
self._configure_fonts()
|
|
|
|
self.params = self._load_or_default_params()
|
|
self.data = None # dict with tau_d, tau_d_shifted, T, DeltaEoE, Delta_n
|
|
self.fit = None # dict, output of BD_Fresnel_func_ni
|
|
# The file loaded this session, if any. A mode change re-reads
|
|
# it, since the two modes need different columns. Kept even if
|
|
# that re-read fails, so switching back can load it again.
|
|
# Deliberately not taken from the saved settings: the data file
|
|
# is not restored at launch.
|
|
self._session_data_path = None
|
|
|
|
self._mechanism_rows = []
|
|
self._build_layout()
|
|
self._refresh_param_fields_from_state()
|
|
self._recalc_beam_params(refresh_display=True)
|
|
# Nothing imported and nothing fitted yet, so this leaves both
|
|
# Fit and Export disabled on a fresh launch -- including when
|
|
# last_settings.json restores a previous session's parameters,
|
|
# since the data file itself is not restored with them.
|
|
self._update_action_buttons()
|
|
|
|
# ------------------------------------------------------------------
|
|
# Fonts (same approach as zscan_gui.py)
|
|
# ------------------------------------------------------------------
|
|
|
|
def _configure_fonts(self):
|
|
available = set(tkfont.families(self))
|
|
available_lower = {f.lower(): f for f in available}
|
|
chosen = None
|
|
for preferred in self.PREFERRED_FONT_FAMILIES:
|
|
if preferred.lower() in available_lower:
|
|
chosen = available_lower[preferred.lower()]
|
|
break
|
|
if chosen is None:
|
|
chosen = "TkDefaultFont"
|
|
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)
|
|
ttk.Style(self).configure(".", font=self.ui_font)
|
|
|
|
# ------------------------------------------------------------------
|
|
# Settings persistence
|
|
# ------------------------------------------------------------------
|
|
|
|
def _load_or_default_params(self) -> BDFresnelParams:
|
|
if os.path.isfile(SETTINGS_PATH):
|
|
try:
|
|
p = load_settings(SETTINGS_PATH)
|
|
print(f"bd_fresnel_gui: previous settings loaded from {SETTINGS_PATH}.")
|
|
if not (p.pathname and os.path.isfile(os.path.join(p.pathname, p.filename))):
|
|
p.filename = ""
|
|
p.pathname = ""
|
|
return p
|
|
except Exception as exc:
|
|
print(f"bd_fresnel_gui: could not load {SETTINGS_PATH} ({exc}); using defaults.")
|
|
return BDFresnelParams()
|
|
|
|
def _save_settings(self):
|
|
try:
|
|
save_settings(self.params, SETTINGS_PATH)
|
|
except Exception as exc:
|
|
print(f"bd_fresnel_gui: failed to save settings: {exc}")
|
|
|
|
# ------------------------------------------------------------------
|
|
# Layout
|
|
# ------------------------------------------------------------------
|
|
|
|
def _build_layout(self):
|
|
outer = ttk.PanedWindow(self, orient="horizontal")
|
|
outer.pack(fill="both", expand=True)
|
|
|
|
left_container = ttk.Frame(outer, width=400)
|
|
outer.add(left_container, weight=0)
|
|
|
|
canvas = tk.Canvas(left_container, borderwidth=0, highlightthickness=0)
|
|
scrollbar = ttk.Scrollbar(left_container, orient="vertical", command=canvas.yview)
|
|
self.param_frame = ttk.Frame(canvas)
|
|
self.param_frame.bind("<Configure>", lambda e: 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._build_param_fields(self.param_frame)
|
|
|
|
right = ttk.Frame(outer)
|
|
outer.add(right, weight=1)
|
|
|
|
# top toolbar: import/fit/export/exit + filename
|
|
toolbar = ttk.Frame(right)
|
|
toolbar.pack(fill="x", padx=6, pady=6)
|
|
self.import_button = ttk.Button(toolbar, text="Import...", command=self._on_import)
|
|
self.import_button.pack(side="left")
|
|
self.fit_button = ttk.Button(toolbar, text="Fit", command=self._on_fit, state="disabled")
|
|
self.fit_button.pack(side="left", padx=4)
|
|
self.export_button = ttk.Button(toolbar, text="Export...", command=self._on_export, state="disabled")
|
|
self.export_button.pack(side="left")
|
|
ttk.Button(toolbar, text="Exit", command=self._on_exit).pack(side="left", padx=4)
|
|
self.filename_var = tk.StringVar(value="(no file imported)")
|
|
ttk.Label(toolbar, textvariable=self.filename_var, foreground="#444").pack(side="left", padx=(16, 0))
|
|
|
|
self.notebook = ttk.Notebook(right)
|
|
self.notebook.pack(fill="both", expand=True, padx=6, pady=(0, 6))
|
|
|
|
# A single tab holds both plots side by side (Transmission on
|
|
# the left, Deflection on the right), rather than the original
|
|
# app's two separate one-plot tabs.
|
|
self.tab_plots = ttk.Frame(self.notebook)
|
|
self.tab_diag = ttk.Frame(self.notebook)
|
|
self.tab_log = ttk.Frame(self.notebook)
|
|
self.notebook.add(self.tab_plots, text="Fitting")
|
|
self.notebook.add(self.tab_diag, text="Diagnostics")
|
|
self.notebook.add(self.tab_log, text="Parameter log")
|
|
|
|
self.plot_holder = ttk.Frame(self.tab_plots)
|
|
self.plot_holder.pack(fill="both", expand=True)
|
|
|
|
# The diagnostics tab can hold a dozen or more figures (five
|
|
# ESA population surfaces alone), so it scrolls rather than
|
|
# letterboxing everything into one view.
|
|
diag_canvas = tk.Canvas(self.tab_diag, borderwidth=0, highlightthickness=0)
|
|
diag_scroll = ttk.Scrollbar(self.tab_diag, orient="vertical",
|
|
command=diag_canvas.yview)
|
|
self.diag_holder = ttk.Frame(diag_canvas)
|
|
self.diag_holder.bind(
|
|
"<Configure>",
|
|
lambda e: diag_canvas.configure(scrollregion=diag_canvas.bbox("all")))
|
|
diag_canvas.create_window((0, 0), window=self.diag_holder, anchor="nw")
|
|
diag_canvas.configure(yscrollcommand=diag_scroll.set)
|
|
diag_canvas.pack(side="left", fill="both", expand=True)
|
|
diag_scroll.pack(side="right", fill="y")
|
|
|
|
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)
|
|
|
|
status_bar = ttk.Frame(right)
|
|
status_bar.pack(fill="x", padx=6, pady=(0, 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")
|
|
|
|
# Both are held only so the embedded canvases (and the resize
|
|
# bindings they own) survive garbage collection; nothing reads
|
|
# them back.
|
|
self._plot_view = None
|
|
self._diag_canvases = []
|
|
|
|
def _build_param_fields(self, parent):
|
|
self._field_widgets = {}
|
|
|
|
sec = add_section(parent, "Data columns")
|
|
for name, label in DATA_COLUMN_FIELDS:
|
|
w = LabeledEntry(sec, label, getattr(self.params, name), width=6,
|
|
integer=True,
|
|
on_change=lambda n=name: self._on_column_change(n))
|
|
w.pack(fill="x", pady=2)
|
|
self._field_widgets[name] = w
|
|
w = LabeledEntry(sec, "Delimiter", self.params.delimiter, width=6,
|
|
on_change=self._on_delimiter_change)
|
|
w.pack(fill="x", pady=2)
|
|
self._field_widgets["delimiter"] = w
|
|
|
|
sec = add_section(parent, "Mode")
|
|
self._configure_mode_toggle_style()
|
|
self.mode_var = tk.StringVar(value=self.params.mode)
|
|
self._mode_buttons = []
|
|
width = max(len(label) for _, label in MODE_CHOICES)
|
|
for mode, label in MODE_CHOICES:
|
|
b = ttk.Radiobutton(sec, text=label, value=mode, variable=self.mode_var,
|
|
command=self._on_mode_change, style="Mode.Toolbutton",
|
|
width=width)
|
|
b.pack(side="left") # abutting, so the pair reads as one control
|
|
self._mode_buttons.append(b)
|
|
|
|
sec = add_section(parent, "Simulation parameters")
|
|
for name, label, unit, kind in SIM_FIELDS:
|
|
if kind == "int":
|
|
w = LabeledEntry(sec, label, getattr(self.params, name),
|
|
width=6, unit=unit, integer=True,
|
|
on_change=lambda n=name: self._on_int_field_change(n))
|
|
else:
|
|
w = LabeledEntry(sec, label, getattr(self.params, name),
|
|
width=6, unit=unit, nonnegative=True,
|
|
on_change=lambda n=name: self._on_field_change(n))
|
|
w.pack(fill="x", pady=2)
|
|
self._field_widgets[name] = w
|
|
|
|
for title, fields in NUMERIC_FIELD_SECTIONS:
|
|
sec = add_section(parent, title)
|
|
for name, label, unit, nonneg in fields:
|
|
w = LabeledEntry(sec, label, getattr(self.params, name), unit=unit,
|
|
nonnegative=nonneg,
|
|
on_change=lambda n=name: self._on_field_change(n))
|
|
w.pack(fill="x", pady=2)
|
|
self._field_widgets[name] = w
|
|
|
|
sec = add_section(parent, "Mechanisms")
|
|
for i in range(self.params.n_mech):
|
|
row = MechanismRow(sec, i, self._on_mechanism_change)
|
|
row.pack(fill="x", pady=2)
|
|
self._mechanism_rows.append(row)
|
|
|
|
sec = add_section(parent, "Diagnostics")
|
|
self.diagnostics_var = tk.BooleanVar(value=self.params.diagnostics)
|
|
ttk.Checkbutton(sec, text="Show diagnostic plots during Fit",
|
|
variable=self.diagnostics_var,
|
|
command=self._on_diagnostics_change).pack(anchor="w")
|
|
|
|
sec = add_section(parent, "Calculated Parameters (probe)")
|
|
self.calc_ng = LabeledStatic(sec, "n_g (group index)")
|
|
self.calc_ng.pack(fill="x", pady=1)
|
|
self.calc_Tlin = LabeledStatic(sec, "T_lin")
|
|
self.calc_Tlin.pack(fill="x", pady=1)
|
|
self.calc_z0 = LabeledStatic(sec, "z_0 (Rayleigh range)")
|
|
self.calc_z0.pack(fill="x", pady=1)
|
|
|
|
sec = add_section(parent, "Calculated Parameters (pump)")
|
|
self.calc_ngp = LabeledStatic(sec, "n_g (group index)")
|
|
self.calc_ngp.pack(fill="x", pady=1)
|
|
self.calc_Tlinp = LabeledStatic(sec, "T_lin")
|
|
self.calc_Tlinp.pack(fill="x", pady=1)
|
|
self.calc_z0p = LabeledStatic(sec, "z_0 (Rayleigh range)")
|
|
self.calc_z0p.pack(fill="x", pady=1)
|
|
self.calc_I0p = LabeledStatic(sec, "I_0 (peak irradiance)")
|
|
self.calc_I0p.pack(fill="x", pady=1)
|
|
|
|
sec = add_section(parent, "Other")
|
|
self.calc_rho = LabeledStatic(sec, "rho (GVM parameter)")
|
|
self.calc_rho.pack(fill="x", pady=1)
|
|
|
|
# ------------------------------------------------------------------
|
|
# Field / state synchronization
|
|
# ------------------------------------------------------------------
|
|
|
|
def _refresh_param_fields_from_state(self):
|
|
for name, widget in self._field_widgets.items():
|
|
widget.set(getattr(self.params, name))
|
|
for i, row in enumerate(self._mechanism_rows):
|
|
row.set_name(self.params.mech[i].name)
|
|
self.diagnostics_var.set(self.params.diagnostics)
|
|
if self.params.filename:
|
|
self.filename_var.set(self.params.filename)
|
|
self._apply_mode_to_widgets()
|
|
|
|
# ------------------------------------------------------------------
|
|
# Mode
|
|
# ------------------------------------------------------------------
|
|
|
|
def _apply_mode_to_widgets(self):
|
|
"""Makes the panel reflect self.params.mode: the selected radio
|
|
button, whether x_0 can be edited (pump probe fixes it at 0),
|
|
and which mechanisms each pull-down offers."""
|
|
mode = self.params.mode
|
|
self.mode_var.set(mode)
|
|
self._field_widgets["x_0"].set_enabled(mode == MODE_BEAM_DEFLECTION)
|
|
# Pump probe reads no deflection column, so its number is moot.
|
|
self._field_widgets["col_DeltaEoE"].set_enabled(mode == MODE_BEAM_DEFLECTION)
|
|
choices = mechanism_names_for_mode(mode)
|
|
for row in self._mechanism_rows:
|
|
row.set_choices(choices)
|
|
|
|
# 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 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 only draws a border
|
|
on the selected option, so the other looks like a bare label
|
|
rather than something to click. Colours are set explicitly, 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 fit runs -- come first, and the
|
|
selected one then stays identifiable but visibly inactive."""
|
|
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 _on_mode_change(self):
|
|
self._set_mode(self.mode_var.get())
|
|
|
|
def _set_mode(self, mode):
|
|
"""Switches mode, then brings the panel, plots and buttons into
|
|
line with it. Any fit on screen is discarded: it was computed
|
|
with the other mode's x_0 and mechanisms, so it no longer
|
|
describes the current settings."""
|
|
if mode == self.params.mode:
|
|
# Tk fires the command on every click, including a click on
|
|
# the button that is already selected.
|
|
return
|
|
cleared, restored = set_mode(self.params, mode)
|
|
|
|
self._refresh_param_fields_from_state()
|
|
self._reread_session_file(f"cannot be used in {MODE_LABELS[mode]} mode")
|
|
self.params.data_fit = False
|
|
self.fit = None
|
|
self._refresh_plots()
|
|
self._refresh_diagnostics()
|
|
self._update_action_buttons()
|
|
self._save_settings()
|
|
|
|
message = f"Mode: {MODE_LABELS[mode]}."
|
|
if cleared:
|
|
slots = ", ".join(str(i + 1) for i in cleared)
|
|
message += (f" Purely refractive mechanism(s) in slot {slots} set aside;"
|
|
f" they return when you switch back to Beam deflection.")
|
|
if restored:
|
|
slots = ", ".join(str(i + 1) for i in restored)
|
|
message += f" Restored mechanism(s) in slot {slots}."
|
|
self.status_var.set(message)
|
|
print(f"bd_fresnel_gui: {message}")
|
|
|
|
def _set_mode_buttons_enabled(self, enabled: bool):
|
|
"""The fit runs on a worker thread that reads self.params
|
|
throughout, so the mode must not change underneath it."""
|
|
for b in self._mode_buttons:
|
|
b.state(["!disabled"] if enabled else ["disabled"])
|
|
|
|
def _on_field_change(self, field_name):
|
|
widget = self._field_widgets[field_name]
|
|
previous = getattr(self.params, field_name)
|
|
try:
|
|
value = widget.get()
|
|
# float() also accepts "nan", "inf" and overflows like
|
|
# "1e999", none of which any parameter can take; left
|
|
# unchecked they flow into the fit and turn it to NaN.
|
|
if not np.isfinite(value):
|
|
raise ValueError
|
|
except ValueError:
|
|
# Reverted, like the integer fields and the mechanism
|
|
# dialog. (This used to substitute 0.0, silently zeroing
|
|
# e.g. a pulse energy on a typo.)
|
|
print(f"bd_fresnel_gui: '{field_name}' must be a finite real number; "
|
|
f"reverting to {previous}.")
|
|
widget.set(previous)
|
|
return
|
|
if FIELD_IS_NONNEGATIVE[field_name]:
|
|
value = abs(value)
|
|
setattr(self.params, field_name, value)
|
|
widget.set(value)
|
|
print(f"bd_fresnel_gui: {field_name} updated to {value}.")
|
|
|
|
if field_name in CALC_BEAM_PARAMS_FIELDS:
|
|
self._recalc_beam_params(refresh_display=True)
|
|
|
|
if field_name == "shift" and self.data is not None:
|
|
self.data["tau_d_shifted"] = self.data["tau_d"] + self.params.shift
|
|
self._refresh_plots()
|
|
|
|
self._update_fit_button_state()
|
|
self._save_settings()
|
|
|
|
def _on_int_field_change(self, field_name, reread=False):
|
|
"""Shared handler for the positive-integer inputs: the data
|
|
column numbers and the simulation grid point counts."""
|
|
widget = self._field_widgets[field_name]
|
|
previous = getattr(self.params, field_name)
|
|
try:
|
|
value = widget.get_int()
|
|
except ValueError:
|
|
print(f"bd_fresnel_gui: '{field_name}' must be a positive "
|
|
f"integer; reverting to {previous}.")
|
|
widget.set(previous)
|
|
return
|
|
|
|
if value == previous:
|
|
return
|
|
setattr(self.params, field_name, value)
|
|
widget.set(value)
|
|
print(f"bd_fresnel_gui: {field_name} updated to {value}.")
|
|
|
|
if reread:
|
|
self._reread_session_file("cannot be read with these column numbers")
|
|
self._save_settings()
|
|
|
|
def _on_column_change(self, field_name):
|
|
# Anything already imported was read with the old column
|
|
# layout, so re-read it rather than leaving mislabelled data on
|
|
# screen. Re-reading clears the fit for the same reason Import
|
|
# does: it belongs to the previous set of columns.
|
|
self._on_int_field_change(field_name, reread=True)
|
|
|
|
def _on_delimiter_change(self):
|
|
widget = self._field_widgets["delimiter"]
|
|
previous = self.params.delimiter
|
|
value = widget.get_str()
|
|
if value == previous:
|
|
return
|
|
|
|
self.params.delimiter = value
|
|
print(f"bd_fresnel_gui: delimiter updated to {value!r} "
|
|
f"({describe_delimiter(value)}).")
|
|
|
|
# Same reasoning as a column change: whatever is loaded was
|
|
# parsed with the old delimiter, so re-read it.
|
|
self._reread_session_file("cannot be read with this delimiter")
|
|
self._save_settings()
|
|
|
|
def _reread_session_file(self, failure_note):
|
|
"""Re-reads the file imported this session, after a change to how
|
|
it is read: a column number, the delimiter, or the mode. Returns
|
|
whether data is now on screen.
|
|
|
|
On failure the data is cleared rather than kept. It was read
|
|
under the old settings, so keeping it would leave on screen --
|
|
and let Fit and Export use -- data the current settings no
|
|
longer describe; the export log would then name columns the
|
|
data did not come from. The file remains this session's, so the
|
|
next change that makes it readable brings it back.
|
|
|
|
Only a file imported this session is re-read, never the one
|
|
named in the saved settings: the data file is not restored at
|
|
launch, and editing a column number straight after launch must
|
|
neither load it nor complain that it has since moved."""
|
|
path = self._session_data_path
|
|
if path is None:
|
|
return False
|
|
try:
|
|
data = self._read_data_file(path)
|
|
except ColumnConflict as exc:
|
|
# Expected while swapping two column numbers one at a time,
|
|
# so noted in the status bar rather than with a dialog.
|
|
self._clear_loaded_data()
|
|
self.status_var.set(f"{exc}. Data hidden until they differ.")
|
|
return False
|
|
except Exception as exc:
|
|
self._clear_loaded_data()
|
|
messagebox.showerror(
|
|
"File Import Error",
|
|
f"File: {path} {failure_note}.\n\n{exc}\n\n"
|
|
f"It will be read again when the settings allow it.")
|
|
return False
|
|
self.data = data
|
|
self.params.data_fit = False
|
|
self.fit = None
|
|
self._refresh_plots()
|
|
self._refresh_diagnostics()
|
|
self._update_action_buttons()
|
|
print(f"bd_fresnel_gui: re-read {path}.")
|
|
return True
|
|
|
|
def _clear_loaded_data(self):
|
|
"""Removes the data, any fit, and their plots."""
|
|
self.data = None
|
|
self.fit = None
|
|
self.params.data_fit = False
|
|
for child in self.plot_holder.winfo_children():
|
|
child.destroy()
|
|
self._plot_view = None
|
|
self._refresh_diagnostics()
|
|
self._update_action_buttons()
|
|
|
|
def _on_diagnostics_change(self):
|
|
self.params.diagnostics = self.diagnostics_var.get()
|
|
self._save_settings()
|
|
|
|
def _on_mechanism_change(self, index, mechanism_name, reopen_dialog=False):
|
|
previous = self.params.mech[index]
|
|
if reopen_dialog:
|
|
new_mech = open_set_params_dialog(self, mechanism_name, previous)
|
|
if new_mech is not None:
|
|
self.params.mech[index] = new_mech
|
|
else:
|
|
self.params.mech[index] = Mechanism(name=mechanism_name)
|
|
self._mechanism_rows[index].set_name(self.params.mech[index].name)
|
|
self._save_settings()
|
|
|
|
def _recalc_beam_params(self, refresh_display=False):
|
|
calc_beam_params(self.params)
|
|
if refresh_display:
|
|
self.calc_ng.set(f"{self.params.ng:.3f}")
|
|
self.calc_Tlin.set(f"{self.params.Tlin:.3f}")
|
|
self.calc_z0.set(f"{self.params.z_0 * 1e3:.3f} mm")
|
|
self.calc_ngp.set(f"{self.params.ng_p:.3f}")
|
|
self.calc_Tlinp.set(f"{self.params.Tlin_p:.3f}")
|
|
self.calc_z0p.set(f"{self.params.z_0_p * 1e3:.3f} mm")
|
|
self.calc_I0p.set(f"{self.params.I_0_p * 1e-13:.3f} GW/cm^2")
|
|
self.calc_rho.set(f"{self.params.rho:.3f}")
|
|
|
|
def _update_fit_button_state(self):
|
|
"""Fit needs both a data file (it takes its delay range from
|
|
the imported scan) and a valid set of beam/material inputs."""
|
|
ready = self.data is not None and inputs_valid(self.params)
|
|
self.fit_button.config(state="normal" if ready else "disabled")
|
|
|
|
def _update_export_button_state(self):
|
|
"""Export writes the data/fit comparison table and the plot
|
|
image, so it stays disabled until a fit has actually
|
|
completed. Importing a new file clears the fit and disables it
|
|
again."""
|
|
ready = self.data is not None and self.fit is not None
|
|
self.export_button.config(state="normal" if ready else "disabled")
|
|
|
|
def _update_action_buttons(self):
|
|
self._update_fit_button_state()
|
|
self._update_export_button_state()
|
|
|
|
# ------------------------------------------------------------------
|
|
# Import
|
|
# ------------------------------------------------------------------
|
|
|
|
def _read_data_file(self, path) -> dict:
|
|
"""Reads the scan at `path`, taking each quantity from the
|
|
column selected in the "Data columns" box. Raises on a
|
|
malformed file.
|
|
|
|
Beam deflection needs delay, deflection and transmission. Pump
|
|
probe needs only delay and transmission: the DeltaEoE column is
|
|
neither read nor required, so a two-column file will do, and
|
|
the returned "DeltaEoE" and "Delta_n" are None."""
|
|
raw = np.genfromtxt(path, skip_header=1,
|
|
delimiter=resolve_delimiter(self.params.delimiter))
|
|
if raw.ndim == 1:
|
|
raw = raw[None, :]
|
|
|
|
col_tau_d = self.params.col_tau_d
|
|
col_T = self.params.col_T
|
|
col_DeltaEoE = self.params.col_DeltaEoE
|
|
pump_probe = self.params.mode == MODE_PUMP_PROBE
|
|
# Every quantity must come from its own column; nothing else
|
|
# stops T and DeltaE/E being read from the same one.
|
|
used = {"tau_d": col_tau_d, "T": col_T}
|
|
if not pump_probe:
|
|
used["DeltaEoE"] = col_DeltaEoE
|
|
by_column = {}
|
|
for name, col in used.items():
|
|
by_column.setdefault(col, []).append(name)
|
|
clashes = [names for names in by_column.values() if len(names) > 1]
|
|
if clashes:
|
|
detail = "; ".join(f"{' and '.join(n)} are both column {used[n[0]]}"
|
|
for n in clashes)
|
|
raise ColumnConflict(f"Each data column must be different: {detail}")
|
|
if pump_probe:
|
|
needed = max(col_tau_d, col_T)
|
|
else:
|
|
needed = max(col_tau_d, col_T, col_DeltaEoE)
|
|
if raw.shape[1] < needed:
|
|
raise ValueError(
|
|
f"file has {raw.shape[1]} column(s), but the selected "
|
|
f"column numbers need at least {needed}")
|
|
if pump_probe:
|
|
# Only the two columns actually used are checked for gaps,
|
|
# so a blank or partial deflection column left in a
|
|
# pump-probe export does not reject the file.
|
|
raw = raw[:, [col_tau_d - 1, col_T - 1]]
|
|
col_tau_d, col_T = 1, 2
|
|
if np.isnan(raw).any():
|
|
# A delimiter that does not match the file is the usual
|
|
# cause: every line then parses as one unsplittable field
|
|
# and comes back as NaN, so say so rather than leaving the
|
|
# user to guess at "missing values".
|
|
if np.isnan(raw).all():
|
|
raise ValueError(
|
|
f"no numeric data found - the delimiter is set to "
|
|
f"{describe_delimiter(self.params.delimiter)}, which may "
|
|
f"not match this file")
|
|
raise ValueError("file must not have missing values")
|
|
|
|
# 1-based in the GUI, 0-based into the array.
|
|
tau_d = raw[:, col_tau_d - 1]
|
|
T = raw[:, col_T - 1]
|
|
if pump_probe:
|
|
return dict(tau_d=tau_d, tau_d_shifted=tau_d + self.params.shift,
|
|
T=T, DeltaEoE=None, Delta_n=None)
|
|
DeltaEoE = raw[:, col_DeltaEoE - 1]
|
|
|
|
lambda_ = self.params.lambda_ * 1e-9
|
|
l = self.params.l * 1e-3
|
|
w_0 = self.params.w_0 * 1e-6
|
|
w_0_p = self.params.w_0p * 1e-6
|
|
k_0 = 2 * np.pi / lambda_
|
|
Delta_n = DeltaEoE / (k_0 * l * np.sqrt(2 / np.e) * (w_0 / w_0_p) * (2 / np.sqrt(np.pi)))
|
|
|
|
return dict(
|
|
tau_d=tau_d,
|
|
tau_d_shifted=tau_d + self.params.shift,
|
|
T=T, DeltaEoE=DeltaEoE, Delta_n=Delta_n,
|
|
)
|
|
|
|
def _on_import(self):
|
|
initial_dir = self.params.pathname or os.getcwd()
|
|
path = filedialog.askopenfilename(
|
|
title=("Import transmission data" if self.params.mode == MODE_PUMP_PROBE
|
|
else "Import transmission/deflection data"),
|
|
initialdir=initial_dir,
|
|
filetypes=[("Text files", "*.txt"), ("All files", "*.*")],
|
|
)
|
|
if not path:
|
|
print("bd_fresnel_gui: file import cancelled.")
|
|
return
|
|
|
|
try:
|
|
self.data = self._read_data_file(path)
|
|
except Exception as exc:
|
|
messagebox.showerror("File Import Error", f"File: {path} is invalid.\n\n{exc}")
|
|
return
|
|
|
|
self.params.pathname = os.path.dirname(path) + os.sep
|
|
self.params.filename = os.path.basename(path)
|
|
self.params.import_filepath = path
|
|
self._session_data_path = path
|
|
self.params.data_imported = True
|
|
self.params.data_fit = False
|
|
self.fit = None
|
|
|
|
self._refresh_plots()
|
|
self._refresh_diagnostics()
|
|
self._update_action_buttons()
|
|
self.filename_var.set(self.params.filename)
|
|
print(f"bd_fresnel_gui: import of {path} complete.")
|
|
self._save_settings()
|
|
|
|
# ------------------------------------------------------------------
|
|
# Fit (forward simulation)
|
|
# ------------------------------------------------------------------
|
|
|
|
def _on_fit(self):
|
|
if self.data is None:
|
|
return
|
|
self.fit_button.config(state="disabled", text="Processing...")
|
|
self.import_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)
|
|
|
|
# Use the shifted delay values (i.e. the same frame the data
|
|
# is actually plotted/compared/exported in, tau_d + shift) so
|
|
# the simulated fit curve's own delay axis lines up exactly
|
|
# with the data it's being compared against. (Note: the
|
|
# original MATLAB app derived this from the raw, unshifted
|
|
# tau_d instead -- a real frame mismatch whenever shift != 0,
|
|
# since refresh_plots.m/pb_Export_Callback.m both compare
|
|
# against the shifted values. This is a deliberate correction,
|
|
# not a faithfulness gap.)
|
|
self.params.T_d_min = float(np.min(self.data["tau_d_shifted"])) / self.params.tau_p
|
|
self.params.T_d_max = float(np.max(self.data["tau_d_shifted"])) / self.params.tau_p
|
|
# T_d_num is no longer forced here -- it is an input in the
|
|
# Simulation Parameters box, defaulting to the 150 this line
|
|
# used to hard-code.
|
|
|
|
thread = threading.Thread(target=self._fit_worker, daemon=True)
|
|
thread.start()
|
|
|
|
def _fit_worker(self):
|
|
t0 = time.time()
|
|
try:
|
|
fit = BD_Fresnel_func_ni(self.params)
|
|
elapsed = time.time() - t0
|
|
self.after(0, self._on_fit_success, fit, elapsed)
|
|
except Exception:
|
|
tb = traceback.format_exc()
|
|
self.after(0, self._on_fit_error, tb)
|
|
|
|
def _on_fit_success(self, fit, elapsed):
|
|
self.fit = fit
|
|
self.params.data_fit = True
|
|
self._refresh_plots()
|
|
self._refresh_diagnostics()
|
|
|
|
self.log_text.delete("1.0", "end")
|
|
self.log_text.insert("1.0", self._build_log_text())
|
|
|
|
self.fit_button.config(text="Fit")
|
|
self.import_button.config(state="normal")
|
|
self._set_mode_buttons_enabled(True)
|
|
self._update_action_buttons()
|
|
self.progress.stop()
|
|
self.status_var.set(f"Fit complete in {elapsed:.2f} s.")
|
|
print(f"bd_fresnel_gui: fitting complete. Elapsed time: {elapsed:.2f} s.")
|
|
self._save_settings()
|
|
|
|
def _on_fit_error(self, tb_text):
|
|
self.fit_button.config(text="Fit")
|
|
self.import_button.config(state="normal")
|
|
self._set_mode_buttons_enabled(True)
|
|
# Export stays available only if an earlier fit succeeded and
|
|
# is still on screen; _update_export_button_state decides.
|
|
self._update_action_buttons()
|
|
self.progress.stop()
|
|
self.status_var.set("Error.")
|
|
self.log_text.delete("1.0", "end")
|
|
self.log_text.insert("1.0", tb_text)
|
|
self.notebook.select(self.tab_log)
|
|
messagebox.showerror("Fit failed", tb_text.strip().splitlines()[-1])
|
|
|
|
# ------------------------------------------------------------------
|
|
# Plotting
|
|
# ------------------------------------------------------------------
|
|
|
|
def _get_plot_context(self):
|
|
"""Computes the data/fit arrays, axis scale, and shared axis
|
|
ranges used by every plot (the two live tabs and the combined
|
|
export image), so they all stay perfectly consistent."""
|
|
tau_d = self.data["tau_d"]
|
|
tau_d_shifted = self.data["tau_d_shifted"]
|
|
n_pts = len(tau_d)
|
|
# Base marker size comes from the active rc context (6 pt on
|
|
# screen, 3 pt in print), shrinking on dense scans so the
|
|
# points stay distinguishable instead of merging into a band.
|
|
# The markers are solid dots, so the size can go right down
|
|
# without the marker degrading -- there is no ring thickness
|
|
# to keep clear of.
|
|
import matplotlib
|
|
base_marker = matplotlib.rcParams["lines.markersize"]
|
|
marker_size = (max(1.0, base_marker * 100 / n_pts)
|
|
if n_pts > 100 else base_marker)
|
|
|
|
delta_tau_d = abs(np.max(tau_d) - np.min(tau_d))
|
|
if delta_tau_d > 1000 ** 2:
|
|
scale, scale_label = 1000 ** 2, "ns"
|
|
elif delta_tau_d > 1000:
|
|
scale, scale_label = 1000, "ps"
|
|
else:
|
|
scale, scale_label = 1, "fs"
|
|
tau_d_disp = tau_d_shifted / scale
|
|
|
|
has_fit = self.fit is not None and self.params.data_fit
|
|
# Pump-probe data carries no deflection column, and has no
|
|
# Deflection panel to size.
|
|
has_deflection = self.data["DeltaEoE"] is not None
|
|
if has_fit:
|
|
fit_tau_d_disp = self.fit["tau_d"] / scale
|
|
T_points = np.concatenate([self.data["T"], self.fit["T"]])
|
|
DeltaEoE_points = (np.concatenate([self.data["DeltaEoE"], self.fit["DeltaEoE"]])
|
|
if has_deflection else None)
|
|
else:
|
|
fit_tau_d_disp = None
|
|
T_points = self.data["T"]
|
|
DeltaEoE_points = self.data["DeltaEoE"]
|
|
|
|
# x-axis covers only the data's delay range (matching the
|
|
# original MATLAB app's xlim(...) behavior). The fit curve's
|
|
# own simulated grid can extend marginally beyond this range
|
|
# (floating-point grid construction), but each plotted line
|
|
# is given an explicit clip path bound to the axes' patch, so
|
|
# any such excess is cleanly cut off at the border rather than
|
|
# visibly overflowing it.
|
|
x_min, x_max = np.min(tau_d_disp), np.max(tau_d_disp)
|
|
|
|
return dict(
|
|
tau_d_disp=tau_d_disp, fit_tau_d_disp=fit_tau_d_disp, has_fit=has_fit,
|
|
marker_size=marker_size,
|
|
T_points=T_points, DeltaEoE_points=DeltaEoE_points,
|
|
x_min=x_min, x_max=x_max, scale_label=scale_label,
|
|
)
|
|
|
|
# Each panel is drawn in a single colour: red for Transmission,
|
|
# blue for Deflection. Data markers and the fit line within one
|
|
# panel share that colour and are told apart by their style
|
|
# (solid dots vs. a solid line), so the two panels stay
|
|
# visually distinct from each other at a glance.
|
|
TRANSMISSION_COLOR = "r"
|
|
DEFLECTION_COLOR = "b"
|
|
|
|
# On-screen the combined figure is drawn large (it gets letterboxed
|
|
# into whatever space the window gives it). The exported image is
|
|
# built at its true final size instead of being scaled down from
|
|
# the screen figure -- 6.5 in wide at 300 dpi, i.e. 1950 px, which
|
|
# is a full text-column width on US Letter with 1 in margins. The
|
|
# export height keeps the on-screen aspect ratio.
|
|
SCREEN_FIGSIZE = (12.0, 5.0)
|
|
# Pump-probe mode shows the Transmission panel alone. The figure is
|
|
# half the width at the same height, so the panel comes out the
|
|
# size it is in the side-by-side figure rather than being
|
|
# stretched to fill the space the Deflection panel used to take.
|
|
SCREEN_FIGSIZE_SINGLE = (SCREEN_FIGSIZE[0] / 2, SCREEN_FIGSIZE[1])
|
|
EXPORT_WIDTH_IN = 6.5
|
|
EXPORT_DPI = 300
|
|
|
|
# Text, marker and line sizes are all specified in points, i.e. in
|
|
# absolute physical units, so they do NOT shrink along with the
|
|
# figure. The export figure is a little over half the width of the
|
|
# on-screen one, so reusing the screen sizes would give it huge
|
|
# labels and markers fat enough to merge into a solid band. Each
|
|
# context therefore gets its own set, with the print sizes chosen
|
|
# to be legible at a 6.5 in column width.
|
|
SCREEN_RC = {
|
|
"font.size": 10, "axes.titlesize": 14, "axes.labelsize": 10,
|
|
"xtick.labelsize": 10, "ytick.labelsize": 10, "legend.fontsize": 10,
|
|
"lines.linewidth": 1.5, "lines.markersize": 6,
|
|
# Same trimming as the print style below: these pads sit in the
|
|
# margin between the axes and the figure edge, so cutting them
|
|
# hands the space back to the plots and to the label text.
|
|
"axes.labelpad": 2.0, "axes.titlepad": 3.0,
|
|
"xtick.major.pad": 2.0, "ytick.major.pad": 2.0,
|
|
}
|
|
PRINT_RC = {
|
|
"font.size": 8, "axes.titlesize": 9, "axes.labelsize": 8,
|
|
"xtick.labelsize": 7, "ytick.labelsize": 7, "legend.fontsize": 7,
|
|
"lines.linewidth": 1.0, "lines.markersize": 3,
|
|
# Tightened from the matplotlib defaults (labelpad 4, tick pad
|
|
# 3.5, titlepad 6). Each of these sits in the margin between
|
|
# the axes and the figure edge, so trimming them hands the
|
|
# space back to the plots without changing the canvas size.
|
|
"axes.labelpad": 2.0, "axes.titlepad": 3.0,
|
|
"xtick.major.pad": 2.0, "ytick.major.pad": 2.0,
|
|
}
|
|
|
|
# tight_layout's pad, in multiples of the font size. The 1.08
|
|
# default leaves a wide dead border on every side; 0.25 keeps a
|
|
# hairline so nothing touches the edge. Reclaiming that border is
|
|
# what pays for the larger on-screen text below.
|
|
EXPORT_LAYOUT_PAD = 0.25
|
|
SCREEN_LAYOUT_PAD = 0.25
|
|
|
|
# The on-screen figure is letterboxed into whatever space the
|
|
# window gives it, which is usually well under the 12 in it is
|
|
# built at. Text is sized in points, so it does not shrink with
|
|
# the figure: at a typical window size the labels take up a third
|
|
# more of the canvas than the layout allowed for, and run off the
|
|
# edge. Scaling the text with the figure keeps the proportions the
|
|
# layout was computed for. The floor stops it becoming unreadable
|
|
# in a very small window.
|
|
MIN_SCREEN_TEXT_SCALE = 0.45
|
|
|
|
# Multiplier on the on-screen text size, paid for by the margin
|
|
# space reclaimed above. 1.0 would keep the text proportional to
|
|
# the 12 in reference figure; anything higher trades plot area for
|
|
# legibility, which is the right trade on screen (unlike the
|
|
# export, where the figure is already at its final printed size).
|
|
SCREEN_TEXT_BOOST = 1.35
|
|
|
|
def _rescale_screen_text(self, fig, axes, width_in=None):
|
|
# Text is proportioned to the side-by-side figure's width.
|
|
# `width_in` defaults to this figure's own width; pump probe's
|
|
# single panel passes the width the side-by-side figure would
|
|
# have in the same window instead, so the text stays the same
|
|
# size whichever mode is selected.
|
|
width_in = width_in or fig.get_size_inches()[0]
|
|
# Floor applied last, so it is a true minimum: folding the
|
|
# boost in afterwards would raise the effective floor and let
|
|
# a very small window clip again.
|
|
scale = max(width_in / self.SCREEN_FIGSIZE[0]
|
|
* self.SCREEN_TEXT_BOOST,
|
|
self.MIN_SCREEN_TEXT_SCALE)
|
|
rc = self.SCREEN_RC
|
|
for ax in axes:
|
|
ax.title.set_fontsize(rc["axes.titlesize"] * scale)
|
|
ax.xaxis.label.set_fontsize(rc["axes.labelsize"] * scale)
|
|
ax.yaxis.label.set_fontsize(rc["axes.labelsize"] * scale)
|
|
# Set through tick_params, not on the label artists: the
|
|
# axis rebuilds those on the next draw and would discard a
|
|
# size set directly on them.
|
|
ax.tick_params(axis="x", labelsize=rc["xtick.labelsize"] * scale)
|
|
ax.tick_params(axis="y", labelsize=rc["ytick.labelsize"] * scale)
|
|
legend = ax.get_legend()
|
|
if legend is not None:
|
|
for text in legend.get_texts():
|
|
text.set_fontsize(rc["legend.fontsize"] * scale)
|
|
|
|
@staticmethod
|
|
def _hide_colliding_boundary_labels(fig, ax_left, ax_right):
|
|
"""With the panels sharing a spine, the left panel's rightmost
|
|
x tick labels can run into the right panel's leftmost ones.
|
|
Both panels span the same delay range, so how many collide
|
|
depends on the range and the label widths -- a narrow scan
|
|
labelled '-0.4', '-0.2', ... crowds the join far more than a
|
|
wide one labelled '-2', '0', '2'. Rather than always dropping
|
|
the left panel's last tick (too little in the first case,
|
|
needlessly lossy in the second), the labels are measured once
|
|
laid out and only those actually overlapping are blanked. The
|
|
tick marks themselves stay.
|
|
|
|
The colliding labels are replaced with empty strings rather
|
|
than hidden with set_visible(False): the axis rebuilds its
|
|
tick artists on the next draw, which resets their visibility,
|
|
so hiding does not survive being redrawn or saved to a file."""
|
|
try:
|
|
renderer = fig.canvas.get_renderer()
|
|
except AttributeError:
|
|
from matplotlib.backends.backend_agg import FigureCanvasAgg
|
|
FigureCanvasAgg(fig)
|
|
renderer = fig.canvas.get_renderer()
|
|
|
|
xlim = ax_left.get_xlim()
|
|
fig.draw(renderer)
|
|
|
|
# Cache the untouched tick positions/labels the first time, so
|
|
# that re-running this on an on-screen resize starts from the
|
|
# full set rather than from a previously blanked one.
|
|
if not hasattr(ax_left, "_bd_full_ticks"):
|
|
ax_left._bd_full_ticks = (
|
|
list(ax_left.get_xticks()),
|
|
[t.get_text() for t in ax_left.get_xticklabels()],
|
|
)
|
|
locs, labels = ax_left._bd_full_ticks
|
|
ax_left.set_xticks(locs, labels=labels)
|
|
ax_left.set_xlim(xlim)
|
|
fig.draw(renderer)
|
|
|
|
# The labels that collide sit exactly on the axis limits, where
|
|
# a tick can land a rounding error outside them (1.2 vs
|
|
# 1.2000000000000002). An exact comparison dropped such a
|
|
# label from consideration, so it was never blanked.
|
|
tol = 1e-9 * (max(xlim) - min(xlim))
|
|
lo, hi = min(xlim) - tol, max(xlim) + tol
|
|
right_boxes = [t.get_window_extent(renderer)
|
|
for loc, t in zip(ax_right.get_xticks(),
|
|
ax_right.get_xticklabels())
|
|
if t.get_text() and lo <= loc <= hi]
|
|
if not right_boxes:
|
|
return
|
|
|
|
left_texts = list(ax_left.get_xticklabels())
|
|
kept = list(labels)
|
|
for i in range(len(left_texts) - 1, -1, -1):
|
|
if not labels[i] or not (lo <= locs[i] <= hi):
|
|
continue
|
|
# A little horizontal padding so labels don't sit flush
|
|
# against each other across the join.
|
|
box = left_texts[i].get_window_extent(renderer).expanded(1.4, 1.0)
|
|
if any(box.overlaps(rb) for rb in right_boxes):
|
|
kept[i] = ""
|
|
else:
|
|
break # labels run left to right; the rest are clear
|
|
|
|
if kept != labels:
|
|
ax_left.set_xticks(locs, labels=kept)
|
|
ax_left.set_xlim(xlim)
|
|
|
|
@staticmethod
|
|
def _order_legend(ax, data_line, fit_line):
|
|
"""Legend entries listed as Data over Fit, independent of the
|
|
order the artists were drawn in (the fit is plotted first so
|
|
the data markers sit on top of it)."""
|
|
handles = [data_line] + ([fit_line] if fit_line is not None else [])
|
|
ax.legend(handles=handles, labels=[h.get_label() for h in handles],
|
|
loc="lower right")
|
|
|
|
# The two panels differ only in which signal they draw, its colour,
|
|
# and the axis labelling -- everything else (marker style, clipping,
|
|
# limits, legend order) is shared, so they are described by a table
|
|
# and drawn by one method.
|
|
PANELS = {
|
|
"T": dict(key="T", color=TRANSMISSION_COLOR, ylabel="T (%)",
|
|
title="Transmission", range_key="T_points"),
|
|
"DeltaEoE": dict(key="DeltaEoE", color=DEFLECTION_COLOR,
|
|
ylabel=r"$\Delta E/E$ (%)", title="Deflection",
|
|
range_key="DeltaEoE_points"),
|
|
}
|
|
|
|
def _plot_signal_axis(self, ax, ctx, which, y_on_right=False):
|
|
"""Draws one panel: data as solid dots, fit as a solid line of
|
|
the same colour, Data listed above Fit in the legend.
|
|
|
|
Both series are given an explicit clip path bound to the axes
|
|
patch, because the simulated fit grid can extend a hair past
|
|
the data's delay range and should be cut off at the border
|
|
rather than overflow it.
|
|
"""
|
|
spec = self.PANELS[which]
|
|
key, color = spec["key"], spec["color"]
|
|
|
|
fit_line = None
|
|
if ctx["has_fit"]:
|
|
fit_line, = ax.plot(ctx["fit_tau_d_disp"], 100 * self.fit[key],
|
|
linestyle="-", color=color, label="Fit")
|
|
fit_line.set_clip_on(True)
|
|
fit_line.set_clip_path(ax.patch)
|
|
data_line, = ax.plot(ctx["tau_d_disp"], 100 * self.data[key],
|
|
linestyle="none", marker="o", color=color,
|
|
markeredgewidth=0,
|
|
markersize=ctx["marker_size"], label="Data")
|
|
data_line.set_clip_path(ax.patch)
|
|
|
|
points = ctx[spec["range_key"]]
|
|
ax.grid(False) # no major grid lines
|
|
ax.set_xlim(ctx["x_min"], ctx["x_max"])
|
|
ax.set_ylim(100 * np.min(points), 100 * np.max(points))
|
|
ax.set_xlabel(rf"$\tau_d$ ({ctx['scale_label']})")
|
|
ax.set_ylabel(spec["ylabel"])
|
|
ax.set_title(spec["title"]) # size from rc context
|
|
if y_on_right:
|
|
ax.yaxis.tick_right()
|
|
ax.yaxis.set_label_position("right")
|
|
self._order_legend(ax, data_line, fit_line)
|
|
|
|
def _refresh_plots(self):
|
|
if self.data is None:
|
|
return
|
|
|
|
fig = self._build_combined_figure()
|
|
|
|
for child in self.plot_holder.winfo_children():
|
|
child.destroy()
|
|
self._plot_view = ResizableFigureCanvas(self.plot_holder, fig) # held, see __init__
|
|
|
|
def _build_combined_figure(self, figsize=None, print_style=False):
|
|
"""Builds the figure shown in the plot tab (and saved as the
|
|
export image). In beam-deflection mode it is side by side:
|
|
Transmission on the left, Deflection on the right with its
|
|
y-axis and tick labels moved to the right-hand side. In
|
|
pump-probe mode it is the Transmission panel alone.
|
|
|
|
`figsize` and `print_style` both default to the on-screen
|
|
settings; export passes the smaller print pair. The context is
|
|
computed inside the rc context so that the data marker size it
|
|
picks scales along with the rest."""
|
|
import matplotlib
|
|
from matplotlib.figure import Figure
|
|
|
|
with matplotlib.rc_context(self.PRINT_RC if print_style else self.SCREEN_RC):
|
|
ctx = self._get_plot_context()
|
|
pad = self.EXPORT_LAYOUT_PAD if print_style else self.SCREEN_LAYOUT_PAD
|
|
|
|
if self.params.mode == MODE_PUMP_PROBE:
|
|
# Transmission only: with the probe centred on the pump
|
|
# there is no deflection signal to show.
|
|
fig = Figure(figsize=figsize or self.SCREEN_FIGSIZE_SINGLE)
|
|
ax = fig.subplots(1, 1)
|
|
self._plot_signal_axis(ax, ctx, "T")
|
|
|
|
def relayout(f=fig, a=ax, pad=pad, print_style=print_style):
|
|
# Sizing this panel's text in proportion to itself
|
|
# would double it: alone, the panel is drawn about
|
|
# twice the size it has beside the Deflection
|
|
# panel, since it fills the pane's height. The text
|
|
# instead takes the size the side-by-side figure
|
|
# would give it in the same window, so switching
|
|
# mode never changes the text size.
|
|
if not print_style:
|
|
holder = getattr(f, "_bd_holder_in", None)
|
|
if holder is None: # not embedded in the window yet
|
|
width_in = (f.get_size_inches()[0] * self.SCREEN_FIGSIZE[0]
|
|
/ self.SCREEN_FIGSIZE_SINGLE[0])
|
|
else: # side-by-side figure's letterboxed width
|
|
aspect = self.SCREEN_FIGSIZE[0] / self.SCREEN_FIGSIZE[1]
|
|
width_in = min(holder[0], holder[1] * aspect)
|
|
self._rescale_screen_text(f, (a,), width_in=width_in)
|
|
f.tight_layout(pad=pad)
|
|
|
|
relayout()
|
|
fig._bd_relayout = relayout
|
|
return fig
|
|
|
|
fig = Figure(figsize=figsize or self.SCREEN_FIGSIZE)
|
|
ax_left, ax_right = fig.subplots(1, 2)
|
|
self._plot_signal_axis(ax_left, ctx, "T")
|
|
self._plot_signal_axis(ax_right, ctx, "DeltaEoE", y_on_right=True)
|
|
|
|
# The panels butt directly against each other, sharing one
|
|
# vertical spine. Nothing has to fit between them: the left
|
|
# panel's y-axis is on the left and the right panel's is on
|
|
# the right. The x tick labels do collide at the join,
|
|
# though, and that is dealt with after layout, once the
|
|
# labels have their final positions.
|
|
|
|
def relayout(f=fig, a=ax_left, b=ax_right, pad=pad,
|
|
print_style=print_style):
|
|
# Re-run in full on every on-screen resize. The text is
|
|
# rescaled first, then the margins are recomputed for
|
|
# the new text size -- doing only one of the two would
|
|
# still leave labels clipped or floating.
|
|
if not print_style:
|
|
self._rescale_screen_text(f, (a, b))
|
|
f.tight_layout(pad=pad)
|
|
f.subplots_adjust(wspace=0)
|
|
self._hide_colliding_boundary_labels(f, a, b)
|
|
|
|
relayout()
|
|
fig._bd_relayout = relayout
|
|
return fig
|
|
|
|
# ------------------------------------------------------------------
|
|
# Diagnostics
|
|
# ------------------------------------------------------------------
|
|
|
|
DIAG_FIGSIZE = (7.0, 4.0)
|
|
|
|
# Axis labels as matplotlib mathtext, so Greek letters render as
|
|
# Greek and sub/superscripts sit where they belong rather than
|
|
# showing the literal "tau_p" / "m^2" source. Figure *titles* keep
|
|
# their plain-text form: they double as the Tk frame label and the
|
|
# export filename, neither of which can render mathtext.
|
|
DIAG_LABEL_T = r"$t$ ($\tau_p$)"
|
|
DIAG_LABEL_R = r"$R[t]$ (m$^2$/W)"
|
|
DIAG_LABEL_A = r"$A[t]$ (m/W)"
|
|
DIAG_LABEL_DN = r"$\Delta n$ (unitless)"
|
|
DIAG_LABEL_DA = r"$\Delta\alpha$ (m$^{-1}$)"
|
|
DIAG_RC = {
|
|
"font.size": 9, "axes.titlesize": 11, "axes.labelsize": 9,
|
|
"xtick.labelsize": 8, "ytick.labelsize": 8, "legend.fontsize": 7,
|
|
"lines.linewidth": 1.2,
|
|
}
|
|
|
|
@classmethod
|
|
def _stacked_figure(cls, n_panels):
|
|
"""Blank figure sized for `n_panels` stacked vertically."""
|
|
from matplotlib.figure import Figure
|
|
|
|
height = cls.DIAG_FIGSIZE[1] * (1.75 if n_panels > 1 else 1.0)
|
|
return Figure(figsize=(cls.DIAG_FIGSIZE[0], height))
|
|
|
|
@staticmethod
|
|
def _finish_stacked_figure(fig, title, n_panels):
|
|
"""Lays out a stacked figure. With more than one panel the name
|
|
goes in a figure-level title, leaving each panel free to name
|
|
the quantity it shows; a lone panel carries the name itself."""
|
|
if n_panels > 1:
|
|
fig.suptitle(title)
|
|
fig.tight_layout(rect=(0, 0, 1, 0.96))
|
|
else:
|
|
fig.axes[0].set_title(title)
|
|
fig.tight_layout()
|
|
|
|
def _build_diagnostic_figures(self, diag):
|
|
"""Rebuilds, as a list of (title, Figure), every plot the
|
|
original MATLAB drew under `if diagnostics`:
|
|
|
|
* "Raw response functions from all mechanisms": every
|
|
mechanism's R[t] and A[t] on shared refraction/absorption
|
|
panels (from BD_exp_rise_decay / BD_librational /
|
|
BD_vibrational, which drew one figure each),
|
|
* "Convolved response from all mechanisms": the same
|
|
responses after convolution with the pulse, plus their
|
|
total (from BD_Fresnel_func_ni),
|
|
* the five ESA population surfaces, the excitation
|
|
transmission vs. depth and the probe transmission vs.
|
|
delay (from BD_3_level_triplet).
|
|
"""
|
|
import matplotlib
|
|
|
|
figures = []
|
|
T1 = diag["T1"]
|
|
# The original clipped the summary plot to t = -3 .. T1_max
|
|
# rather than the full convolution window; both response
|
|
# figures use that range so they can be read against each other.
|
|
T_plot_min, T_plot_max = -3.0, diag["T1_max"]
|
|
|
|
with matplotlib.rc_context(self.DIAG_RC):
|
|
# One figure for every mechanism's response function, laid
|
|
# out like the all-mechanisms summary below: the refractive
|
|
# parts R[t] share the top panel and the absorptive parts
|
|
# A[t] the bottom, one curve per mechanism. A panel is drawn
|
|
# only if something lands in it -- a coefficient of zero
|
|
# means the original drew nothing for that part.
|
|
panels = [
|
|
(np.real, "refraction", "Refraction", self.DIAG_LABEL_R),
|
|
(np.imag, "absorption", "Absorption", self.DIAG_LABEL_A),
|
|
]
|
|
panels = [panel for panel in panels
|
|
if any(r[panel[1]] for r in diag["responses"])]
|
|
|
|
if panels:
|
|
# Named to distinguish it from the convolved summary
|
|
# below: this one shows the bare response functions,
|
|
# that one shows them after convolution with the pulse.
|
|
title = "Raw response functions from all mechanisms"
|
|
fig = self._stacked_figure(len(panels))
|
|
for row, (component, key, name, axis_label) in enumerate(panels, start=1):
|
|
ax = fig.add_subplot(len(panels), 1, row)
|
|
for resp in diag["responses"]:
|
|
if not resp[key]:
|
|
continue
|
|
# Numbered with the 1-based mechanism slot, the
|
|
# same numbering the parameter log uses.
|
|
ax.plot(T1, component(resp["R"]),
|
|
label=f"{resp['number']}. {resp['mech_name']}")
|
|
ax.set_xlim(T_plot_min, T_plot_max)
|
|
ax.set_xlabel(self.DIAG_LABEL_T)
|
|
ax.set_ylabel(axis_label)
|
|
ax.set_title(name)
|
|
ax.legend(loc="best")
|
|
self._finish_stacked_figure(fig, title, len(panels))
|
|
figures.append((title, fig))
|
|
|
|
combined = diag.get("combined")
|
|
if combined is not None:
|
|
# The same responses after convolution with the pulse,
|
|
# per mechanism plus their total. Laid out like the raw
|
|
# figure above: the name goes in the figure title and
|
|
# each panel names the quantity it shows.
|
|
title = "Convolved response from all mechanisms"
|
|
fig = self._stacked_figure(2)
|
|
curves, labels = combined["curves"], combined["labels"]
|
|
for ax, part, ylabel, panel in (
|
|
(fig.add_subplot(211), np.real, self.DIAG_LABEL_DN,
|
|
"Index change"),
|
|
(fig.add_subplot(212), np.imag, self.DIAG_LABEL_DA,
|
|
"Absorption change")):
|
|
for label, curve in zip(labels, curves):
|
|
ax.plot(T1, part(curve), label=label)
|
|
ax.plot(T1, part(combined["total"]), label="Total")
|
|
ax.set_xlim(T_plot_min, T_plot_max)
|
|
ax.set_xlabel(self.DIAG_LABEL_T)
|
|
ax.set_ylabel(ylabel)
|
|
ax.set_title(panel)
|
|
ax.legend(loc="best")
|
|
self._finish_stacked_figure(fig, title, 2)
|
|
figures.append((title, fig))
|
|
|
|
esa = diag.get("esa")
|
|
if esa:
|
|
figures.extend(self._build_esa_figures(esa))
|
|
|
|
return figures
|
|
|
|
@staticmethod
|
|
def _pop_mathtext(name: str) -> str:
|
|
"""Turns a population name into mathtext: N_S_0 -> N_{S_0}, so
|
|
the state renders with its electronic term as a nested
|
|
subscript instead of showing the raw underscores."""
|
|
parts = name.split("_")
|
|
if len(parts) == 3:
|
|
return f"{parts[0]}_{{{parts[1]}_{parts[2]}}}"
|
|
return name.replace("_", r"\_")
|
|
|
|
def _build_esa_figures(self, esa):
|
|
"""The seven BD_3_level_triplet diagnostic figures."""
|
|
from matplotlib.figure import Figure
|
|
|
|
figures = []
|
|
# Same "N. " prefix as the response figures, so every diagnostic
|
|
# names the mechanism slot it came from.
|
|
prefix = f"{esa['number']}. " if esa.get("number") else ""
|
|
Y_interp, N0 = esa["Y_interp"], esa["N0"]
|
|
z, L = esa["z"], esa["L"]
|
|
tau_d, tau_e = esa["tau_d"], esa["tau_e"]
|
|
rad_fac = esa["rad_fac"]
|
|
|
|
# Surfaces are drawn at the full-irradiance radial slice and
|
|
# drop the final depth step, exactly as the original's
|
|
# Y_interp(:,1:end-1,n,1) indexing did (that last z point is
|
|
# never written by the propagation loop).
|
|
TAU, Z = np.meshgrid(tau_d / tau_e, z[:-1] / L, indexing="ij")
|
|
for n, pop in enumerate(esa["pop_names"]):
|
|
fig = Figure(figsize=self.DIAG_FIGSIZE)
|
|
ax = fig.add_subplot(111, projection="3d")
|
|
ax.plot_surface(TAU, Z, Y_interp[:, :-1, n, 0] / N0,
|
|
cmap="viridis", linewidth=0, antialiased=True)
|
|
pop_math = self._pop_mathtext(pop)
|
|
ax.set_xlabel(r"$T$ ($\tau_e$)")
|
|
ax.set_ylabel(r"$Z$ ($L$)")
|
|
ax.set_zlabel(f"${pop_math}/N_t$")
|
|
ax.set_title(f"{prefix}Population of ${pop_math}$ vs. time")
|
|
fig.tight_layout()
|
|
figures.append((f"{prefix}Population of {pop}", fig))
|
|
|
|
# The excitation and probe transmission plots differ only in
|
|
# their x axis and the array plotted against it. The last
|
|
# radial factor is exactly 0, making the excitation ratio a
|
|
# 0/0: MATLAB produced a silent NaN and drew nothing for that
|
|
# trace, which errstate reproduces without a warning.
|
|
with np.errstate(invalid="ignore", divide="ignore"):
|
|
excitation_T = esa["I_0_e_arr"] / esa["I_0_e_norm"]
|
|
|
|
for x_vals, y_vals, xlabel, title in (
|
|
(z / L, excitation_T, r"$Z$ ($L$)",
|
|
"Transmission of excitation vs. position"),
|
|
(tau_d / tau_e, esa["I_p_end"], r"$T_d$ ($\tau_e$)",
|
|
"Transmission of probe vs. delay")):
|
|
fig = Figure(figsize=self.DIAG_FIGSIZE)
|
|
ax = fig.add_subplot(111)
|
|
# One trace per radial irradiance factor, labelled with
|
|
# that factor to 2 significant figures as the original's
|
|
# legend was.
|
|
for k, fac in enumerate(rad_fac):
|
|
ax.plot(x_vals, y_vals[:, k], label=f"{fac:.2g}")
|
|
ax.set_xlim(np.min(x_vals), np.max(x_vals))
|
|
ax.set_xlabel(xlabel)
|
|
ax.set_ylabel(r"$T$ (unitless)")
|
|
ax.set_title(prefix + title)
|
|
ax.legend(loc="lower left", title=r"$I_e[r]/I_{e0}$", frameon=False)
|
|
fig.tight_layout()
|
|
figures.append((prefix + title, fig))
|
|
|
|
return figures
|
|
|
|
def _refresh_diagnostics(self):
|
|
for child in self.diag_holder.winfo_children():
|
|
child.destroy()
|
|
self._diag_canvases = []
|
|
|
|
diag = self.fit.get("diagnostics") if self.fit else None
|
|
if diag is None:
|
|
message = ("Diagnostics are off. Tick \"Show diagnostic plots "
|
|
"during Fit\" in the parameter panel and run Fit "
|
|
"again to populate this tab.")
|
|
ttk.Label(self.diag_holder, text=message, wraplength=600,
|
|
padding=20, foreground="#444").pack(anchor="w")
|
|
return
|
|
|
|
if diag.get("note"):
|
|
ttk.Label(self.diag_holder, text=diag["note"], wraplength=600,
|
|
padding=(20, 12), foreground="#444").pack(anchor="w")
|
|
|
|
for title, fig in self._build_diagnostic_figures(diag):
|
|
frame = ttk.LabelFrame(self.diag_holder, text=title, padding=4)
|
|
frame.pack(fill="x", padx=8, pady=6)
|
|
canvas = FigureCanvasTkAgg(fig, master=frame)
|
|
canvas.draw()
|
|
canvas.get_tk_widget().pack()
|
|
# Held so the canvases are not garbage collected.
|
|
self._diag_canvases.append(canvas)
|
|
|
|
# ------------------------------------------------------------------
|
|
# Export
|
|
# ------------------------------------------------------------------
|
|
|
|
def _on_export(self):
|
|
if self.data is None or self.fit is None:
|
|
return
|
|
default_name = self.params.filename.replace(".txt", "_fit.txt")
|
|
path = filedialog.asksaveasfilename(
|
|
title="Select filename for fit export",
|
|
initialdir=self.params.pathname or os.getcwd(),
|
|
initialfile=default_name,
|
|
defaultextension=".txt",
|
|
filetypes=[("Text files", "*.txt"), ("All files", "*.*")],
|
|
)
|
|
if not path:
|
|
print("bd_fresnel_gui: fit export cancelled.")
|
|
return
|
|
|
|
try:
|
|
T_interp = np.interp(self.data["tau_d_shifted"], self.fit["tau_d"], self.fit["T"])
|
|
if self.params.mode == MODE_PUMP_PROBE:
|
|
# No deflection was imported, so none is exported: the
|
|
# fitted deflection would be identically zero anyway,
|
|
# with the probe centred on the pump.
|
|
export_data = np.column_stack([
|
|
self.data["tau_d_shifted"], self.data["T"], T_interp])
|
|
header = "Delay (fs), T (Data), T (Fit)"
|
|
else:
|
|
DeltaEoE_interp = np.interp(self.data["tau_d_shifted"], self.fit["tau_d"], self.fit["DeltaEoE"])
|
|
Delta_n_interp = np.interp(self.data["tau_d_shifted"], self.fit["tau_d"], self.fit["Delta_n"])
|
|
|
|
export_data = np.column_stack([
|
|
self.data["tau_d_shifted"], self.data["DeltaEoE"], self.data["T"], self.data["Delta_n"],
|
|
DeltaEoE_interp, T_interp, Delta_n_interp,
|
|
])
|
|
header = ("Delay (fs), DeltaE / E (Data), T (Data), Delta_n (data), "
|
|
"DeltaE / E (Fit), T (Fit), Delta_n (fit)")
|
|
np.savetxt(path, export_data, delimiter=",", fmt="%.8g",
|
|
header=header, comments="", newline="\r\n")
|
|
|
|
# Images before the log: the log lists every file the
|
|
# export produced, so it has to be written last, once the
|
|
# image filenames are known.
|
|
image_paths = self._export_plot_images(path)
|
|
self._write_export_log(path, image_paths)
|
|
print(f"bd_fresnel_gui: export of {path} complete.")
|
|
self._save_settings()
|
|
except Exception:
|
|
messagebox.showerror("Export failed", traceback.format_exc().strip().splitlines()[-1])
|
|
|
|
def _export_plot_images(self, export_path):
|
|
"""Saves the fit figure as .jpg and .svg alongside the exported
|
|
data/log files -- side by side as "_combined" in beam
|
|
deflection, the Transmission panel alone as "_transmission" in
|
|
pump probe -- plus every diagnostic figure as .jpg when the fit
|
|
was run with diagnostics enabled. Returns the paths written, in
|
|
the order written."""
|
|
if self.data is None:
|
|
return []
|
|
|
|
# Built fresh here rather than reusing the on-screen figure:
|
|
# the displayed one is a different size and gets resized again
|
|
# by ResizableFigureCanvas as the window changes, so its layout
|
|
# is both wrong for print and potentially stale.
|
|
# Pump probe exports its lone Transmission panel at half the
|
|
# width and the same height, i.e. at exactly the size that
|
|
# panel has inside the side-by-side export -- 3.25 in, a
|
|
# standard single-column width. It is named for what it
|
|
# contains rather than "_combined".
|
|
height = self.EXPORT_WIDTH_IN * self.SCREEN_FIGSIZE[1] / self.SCREEN_FIGSIZE[0]
|
|
if self.params.mode == MODE_PUMP_PROBE:
|
|
width, stem = self.EXPORT_WIDTH_IN / 2, "_transmission"
|
|
else:
|
|
width, stem = self.EXPORT_WIDTH_IN, "_combined"
|
|
fig = self._build_combined_figure(figsize=(width, height), print_style=True)
|
|
written = []
|
|
for suffix, fmt, dpi in ((f"{stem}.jpg", "jpg", self.EXPORT_DPI),
|
|
(f"{stem}.svg", "svg", None)):
|
|
path = self._sibling_path(export_path, suffix)
|
|
fig.savefig(path, format=fmt, **({"dpi": dpi} if dpi else {}))
|
|
written.append(path)
|
|
|
|
written.extend(self._export_diagnostic_images(export_path))
|
|
return written
|
|
|
|
# Short filename suffixes for the figures that would otherwise get
|
|
# unwieldy names from their (deliberately descriptive) titles.
|
|
# Anything not listed falls back to a slug of its title.
|
|
DIAG_FILE_SUFFIXES = {
|
|
"Raw response functions from all mechanisms": "_raw_response",
|
|
"Convolved response from all mechanisms": "_convolved_response",
|
|
}
|
|
|
|
@staticmethod
|
|
def _sibling_path(export_path: str, suffix: str) -> str:
|
|
"""Names a file alongside the exported data, e.g.
|
|
scan_fit.txt -> scan_fit_combined.jpg."""
|
|
return export_path.replace(".txt", suffix)
|
|
|
|
@staticmethod
|
|
def _filename_slug(title: str) -> str:
|
|
"""Turns a figure title into a safe filename fragment."""
|
|
slug = "".join(c if c.isalnum() else "_" for c in title.lower())
|
|
return "_".join(part for part in slug.split("_") if part)
|
|
|
|
def _export_diagnostic_images(self, export_path):
|
|
"""Writes each diagnostic figure as a .jpg next to the exported
|
|
data. Silently does nothing when the fit carries no diagnostics
|
|
(the checkbox was off), since they are an optional extra rather
|
|
than part of the standard export set.
|
|
|
|
Figures are saved at the size they were built for the tab
|
|
rather than being rescaled to the fit image's 6.5 in width:
|
|
their text is sized in points, so resizing them would need the
|
|
same rescaling the on-screen figure does, and at 300 dpi a
|
|
7 in figure is already 2100 px across.
|
|
"""
|
|
diag = self.fit.get("diagnostics") if self.fit else None
|
|
if not diag:
|
|
return []
|
|
|
|
written = []
|
|
used = set()
|
|
for title, fig in self._build_diagnostic_figures(diag):
|
|
suffix = self.DIAG_FILE_SUFFIXES.get(
|
|
title, f"_diag_{self._filename_slug(title)}")
|
|
# Nothing currently produces two figures with the same
|
|
# title, but a duplicate would silently overwrite the
|
|
# earlier file, so disambiguate rather than lose one.
|
|
base, n = suffix, 2
|
|
while suffix in used:
|
|
suffix, n = f"{base}_{n}", n + 1
|
|
used.add(suffix)
|
|
|
|
path = self._sibling_path(export_path, f"{suffix}.jpg")
|
|
fig.savefig(path, format="jpg", dpi=self.EXPORT_DPI)
|
|
written.append(path)
|
|
|
|
if written:
|
|
print(f"bd_fresnel_gui: wrote {len(written)} diagnostic image(s) "
|
|
f"at {self.EXPORT_DPI} dpi.")
|
|
return written
|
|
|
|
def _build_log_text(self, exported_files=None):
|
|
"""
|
|
Builds the full log report as a string. Used both to write the
|
|
_log.txt file on Export and to populate the Log tab immediately
|
|
after a Fit completes (nothing has been written at that point,
|
|
so leave exported_files unset and the file manifest is
|
|
omitted).
|
|
|
|
Section order matches the GUI's left-panel field order top to
|
|
bottom: Data Columns -> Mode -> Simulation grid (not itself a GUI
|
|
field, kept as a preamble) -> Pump (Excitation) Beam -> Probe
|
|
Beam -> Material @ Pump Wavelength -> Material @ Probe
|
|
Wavelength -> System Geometry -> Mechanisms -> Calculated
|
|
Parameters (probe) -> Calculated Parameters (pump) -> Other
|
|
(rho). The column numbers are 1-based, as entered in the GUI.
|
|
"""
|
|
from bd_fresnel_core import MECHANISM_PARAM_SPECS
|
|
|
|
p = self.params
|
|
lines = []
|
|
lines.append(f"{datetime.datetime.now()}: Begin beam deflection program (bd_fresnel_gui.py).\n")
|
|
lines.append(f"Import data file {p.import_filepath}.\n")
|
|
lines.append(f"Mode: {MODE_LABELS[p.mode]}\n")
|
|
|
|
lines.append("Data Columns:")
|
|
lines.append(f" tau_d column: {p.col_tau_d}")
|
|
lines.append(f" T column: {p.col_T}")
|
|
if p.mode == MODE_PUMP_PROBE:
|
|
lines.append(" DeltaEoE column: not used in Pump probe")
|
|
else:
|
|
lines.append(f" DeltaEoE column: {p.col_DeltaEoE}")
|
|
lines.append(f" Delimiter: {describe_delimiter(p.delimiter)}\n")
|
|
|
|
# The delay grid is included so a run is reproducible from the
|
|
# log alone: T_d_min/T_d_max are not entered but derived from
|
|
# the imported scan's delay range at fit time.
|
|
lines.append("Simulation Parameters:")
|
|
lines.append(f" X_num: {p.X_num}")
|
|
lines.append(f" X_max: {p.X_max} w_0")
|
|
lines.append(f" T_num: {p.T_num}")
|
|
lines.append(f" T_min: {p.T_min} tau_p")
|
|
lines.append(f" T_max: {p.T_max} tau_p")
|
|
lines.append(f" T_d_num: {p.T_d_num}")
|
|
lines.append(f" T_d_min: {p.T_d_min:.6g} tau_p")
|
|
lines.append(f" T_d_max: {p.T_d_max:.6g} tau_p\n")
|
|
|
|
lines.append("Pump (Excitation) Beam:")
|
|
lines.append(f" E_p: {p.E_p} uJ")
|
|
lines.append(f" tau_p_FWHM: {p.tau_p_FWHM} fs")
|
|
lines.append(f" tau_p (HW1/eM): {p.tau_p:6.3f} fs")
|
|
lines.append(f" w_0p: {p.w_0p} um")
|
|
lines.append(f" lambda_p: {p.lambda_p} nm\n")
|
|
|
|
lines.append("Probe Beam:")
|
|
lines.append(f" tau_FWHM: {p.tau_FWHM} fs")
|
|
lines.append(f" tau (HW1/eM): {p.tau:6.3f} fs")
|
|
lines.append(f" w_0: {p.w_0} um")
|
|
lines.append(f" lambda: {p.lambda_} nm\n")
|
|
|
|
lines.append("Material @ Pump Wavelength:")
|
|
lines.append(f" R_p: {p.R_p * 100:6.3f} %")
|
|
lines.append(f" alpha_p: {p.alpha_p:6.3f} cm^-1")
|
|
lines.append(f" n_p: {p.n_p}")
|
|
lines.append(f" dndl_p: {p.dndl_p:6.6f} um^-1")
|
|
lines.append(f" alpha_2d: {p.alpha_2d} e-11 m/W\n")
|
|
|
|
lines.append("Material @ Probe Wavelength:")
|
|
lines.append(f" R: {p.R * 100:6.3f} %")
|
|
lines.append(f" alpha: {p.alpha:6.3f} cm^-1")
|
|
lines.append(f" n: {p.n}")
|
|
lines.append(f" dndl: {p.dndl:6.6f} um^-1\n")
|
|
|
|
lines.append("System Geometry:")
|
|
lines.append(f" l: {p.l} mm")
|
|
lines.append(f" d: {p.d} cm")
|
|
lines.append(f" shift: {p.shift} fs")
|
|
lines.append(f" x_0: {p.x_0} w_0_p\n")
|
|
|
|
for i, mech in enumerate(p.mech):
|
|
if mech.name == "None (both)":
|
|
continue
|
|
lines.append(f"Mechanism {i + 1}:")
|
|
lines.append(f" Type: {mech.name}")
|
|
specs = MECHANISM_PARAM_SPECS.get(mech.name, [])
|
|
for j, (pname, punits) in enumerate(specs):
|
|
spacing = " " * max(1, 20 - len(pname))
|
|
lines.append(f" {pname}:{spacing}{mech.param[j]} {punits}")
|
|
lines.append("")
|
|
|
|
lines.append("Calculated Parameters (probe):")
|
|
lines.append(f" n_g: {p.ng:6.3f}")
|
|
lines.append(f" T_lin: {p.Tlin * 100:6.3f} %")
|
|
lines.append(f" z_0: {p.z_0 * 1e3:6.3f} mm\n")
|
|
|
|
lines.append("Calculated Parameters (pump):")
|
|
lines.append(f" n_g: {p.ng_p:6.3f}")
|
|
lines.append(f" T_lin: {p.Tlin_p * 100:6.3f} %")
|
|
lines.append(f" z_0: {p.z_0_p * 1e3:6.3f} mm")
|
|
lines.append(f" I_0: {p.I_0_p * 1e-13:6.3f} GW/cm^2\n")
|
|
|
|
lines.append("Other:")
|
|
lines.append(f" rho: {p.rho:6.3f}\n")
|
|
|
|
if exported_files:
|
|
# Every file this export run produced. They all land in one
|
|
# directory, so that is named once in the header and the
|
|
# entries are bare filenames. The count varies: the fit
|
|
# figure's .jpg and .svg are always written, and one .jpg per
|
|
# diagnostic figure is added when the fit was run with
|
|
# diagnostics enabled.
|
|
directory = os.path.dirname(exported_files[0]) or "."
|
|
lines.append(f"Exported {len(exported_files)} file(s) to {directory}:")
|
|
for path in exported_files:
|
|
lines.append(f" {os.path.basename(path)}")
|
|
lines.append("")
|
|
lines.append("Please cite the following references when using products from this program.\n")
|
|
lines.append(' 1: Reichert, M., et al. (2014). "Temporal, spectral, and polarization '
|
|
'dependence of the nonlinear optical response of carbon disulfide." Optica 1(6): 436.\n')
|
|
lines.append(' 2: Reichert, M., et al. (2014). "Temporal, spectral, and polarization '
|
|
'dependence of the nonlinear optical response of carbon disulfide: supplementary '
|
|
'material." Optica 1(6): 436.\n')
|
|
lines.append(' 3: Ferdinandus, M. R., et al. (2013). "Beam deflection measurement of time '
|
|
'and polarization resolved ultrafast nonlinear refraction." Opt Lett 38(18): 3518-3521.\n')
|
|
|
|
return "\n".join(lines)
|
|
|
|
def _write_export_log(self, export_path, image_paths=()):
|
|
log_path = self._sibling_path(export_path, "_log.txt")
|
|
# The manifest covers the data file, the images, and this log
|
|
# itself -- everything the export run produced.
|
|
exported = [export_path, *image_paths, log_path]
|
|
text = self._build_log_text(exported_files=exported)
|
|
with open(log_path, "w+", newline="\r\n") as f:
|
|
f.write(text)
|
|
|
|
# ------------------------------------------------------------------
|
|
# Exit
|
|
# ------------------------------------------------------------------
|
|
|
|
def _on_exit(self):
|
|
self._save_settings()
|
|
print("bd_fresnel_gui: end BD_Fresnel_GUI.")
|
|
self.destroy()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
app = BDFresnelApp()
|
|
app.protocol("WM_DELETE_WINDOW", app._on_exit)
|
|
app.mainloop()
|