Upload files to "/"

This commit is contained in:
2026-09-30 15:20:31 +00:00
parent cc67401de9
commit 38c09a4272
4 changed files with 350 additions and 97 deletions
+251 -77
View File
@@ -66,6 +66,8 @@ from bd_fresnel_core import (
load_settings,
MODE_BEAM_DEFLECTION,
MODE_PUMP_PROBE,
RUN_MODE_FITTING,
RUN_MODE_SIMULATION,
mechanism_names_for_mode,
set_mode,
)
@@ -148,14 +150,17 @@ def describe_delimiter(text: str) -> str:
# 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.
# negative. T_d_min/T_d_max are signed and are entered only in
# Simulation mode; in Fitting mode they are taken from the imported
# scan's delay range and the fields are disabled.
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"),
("T_d_min", "T_d_min (delay start)", "tau_p", "signed"),
("T_d_max", "T_d_max (delay end)", "tau_p", "signed"),
]
# The numeric parameter boxes, in panel order. Each entry is
@@ -177,7 +182,7 @@ FIELD_IS_NONNEGATIVE = {
for name, _label, _unit, nonneg in fields
}
FIELD_IS_NONNEGATIVE.update(
{name: True for name, _l, _u, kind in SIM_FIELDS if kind == "float"})
{name: kind == "float" for name, _l, _u, kind in SIM_FIELDS if kind != "int"})
class ColumnConflict(ValueError):
"""Two quantities are set to read from the same data column. Kept
@@ -185,7 +190,8 @@ class ColumnConflict(ValueError):
state while swapping two column numbers, one field at a time."""
# The "Mode" box's radio buttons, in display order: (mode, label). The
# The "Operation 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"),
@@ -193,6 +199,15 @@ MODE_CHOICES = [
]
MODE_LABELS = dict(MODE_CHOICES)
# The run-mode toggle, drawn below the measurement-mode one in the same
# box. Fitting compares against an imported scan; Simulation computes
# the signal from the parameters alone.
RUN_MODE_CHOICES = [
(RUN_MODE_FITTING, "Fitting"),
(RUN_MODE_SIMULATION, "Simulation"),
]
RUN_MODE_LABELS = dict(RUN_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 = [
@@ -537,6 +552,19 @@ class BDFresnelApp(tk.Tk):
def _build_param_fields(self, parent):
self._field_widgets = {}
sec = add_section(parent, "Operation mode")
self._configure_mode_toggle_style()
# Two toggles stacked in one box: what is being measured, then
# whether a measurement is being fitted at all. Each row is its
# own frame so the pairs stack rather than running together.
self.mode_var = tk.StringVar(value=self.params.mode)
self._mode_buttons = self._build_toggle_row(
sec, MODE_CHOICES, self.mode_var, self._on_mode_change)
self.run_mode_var = tk.StringVar(value=self.params.run_mode)
self._run_mode_buttons = self._build_toggle_row(
sec, RUN_MODE_CHOICES, self.run_mode_var, self._on_run_mode_change,
pady=(3, 0))
sec = add_section(parent, "Data columns")
for name, label in DATA_COLUMN_FIELDS:
w = LabeledEntry(sec, label, getattr(self.params, name), width=6,
@@ -549,21 +577,16 @@ class BDFresnelApp(tk.Tk):
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":
if kind == "signed":
# Delay range: entered only in Simulation mode, where
# there is no file to take it from. T_d_min is normally
# negative, so no sign restriction here.
w = LabeledEntry(sec, label, getattr(self.params, name),
width=6, unit=unit,
on_change=lambda n=name: self._on_field_change(n))
elif 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))
@@ -636,24 +659,63 @@ class BDFresnelApp(tk.Tk):
# ------------------------------------------------------------------
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."""
"""Makes the panel reflect self.params.mode and .run_mode: the
selected radio buttons, whether x_0 can be edited (pump probe
fixes it at 0), which mechanisms each pull-down offers, and
which inputs Simulation mode takes over or gives up."""
mode = self.params.mode
simulating = self.params.run_mode == RUN_MODE_SIMULATION
self.mode_var.set(mode)
self.run_mode_var.set(self.params.run_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)
# Simulation reads no file, so the column numbers and delimiter
# have nothing to describe.
for name in ("col_tau_d", "col_T", "delimiter"):
self._field_widgets[name].set_enabled(not simulating)
# Pump probe reads no deflection column, so its number is moot.
self._field_widgets["col_DeltaEoE"].set_enabled(
mode == MODE_BEAM_DEFLECTION and not simulating)
# The delay range is entered only when there is no scan to take
# it from; in Fitting mode it is overwritten at fit time.
for name in ("T_d_min", "T_d_max"):
self._field_widgets[name].set_enabled(simulating)
self.import_button.config(state="disabled" if simulating else "normal")
self.fit_button.config(text=self.run_action_label)
# Selection colour of Tk's "default" theme (its radio-button
# indicator), so the toggle matches the rest of the panel.
MODE_SELECTED_BG = "#4a6984"
@staticmethod
def _build_toggle_row(parent, choices, variable, command, pady=0):
"""One segmented toggle: equal-width buttons packed edge to edge
so the pair reads as a single control. Returns the buttons.
The width is taken across both toggles' labels, not just this
row's, so the two rows line up as one block."""
row = ttk.Frame(parent)
row.pack(anchor="w", pady=pady)
width = max(len(label)
for group in (MODE_CHOICES, RUN_MODE_CHOICES)
for _, label in group)
buttons = []
for value, label in choices:
b = ttk.Radiobutton(row, text=label, value=value, variable=variable,
command=command, style="Mode.Toolbutton",
width=width)
b.pack(side="left")
buttons.append(b)
return buttons
def _configure_mode_toggle_style(self):
"""The Mode box's two radio buttons drawn as a segmented toggle:
"""The Operation mode box's two radio buttons drawn as a segmented toggle:
a pair of equal-width buttons, the selected one filled.
Built on ttk's Toolbutton, but with a border on both states.
@@ -678,9 +740,50 @@ class BDFresnelApp(tk.Tk):
("disabled", "#a3a3a3"),
("selected", "white")])
@property
def run_action_label(self):
"""What the Fit button is called in the current run mode."""
return ("Simulate" if self.params.run_mode == RUN_MODE_SIMULATION
else "Fit")
def _on_mode_change(self):
self._set_mode(self.mode_var.get())
def _on_run_mode_change(self):
self._set_run_mode(self.run_mode_var.get())
def _set_run_mode(self, run_mode):
"""Switches between fitting an imported scan and simulating
without one. Any result on screen is discarded: a fit describes
a measurement that Simulation mode does not show, and a
simulation was computed over a hand-entered delay range that
Fitting mode replaces with the file's."""
if run_mode == self.params.run_mode:
return # Tk fires on every click, re-selection included
self.params.run_mode = run_mode
simulating = run_mode == RUN_MODE_SIMULATION
# The imported scan is kept in params while simulating, so
# switching back restores it rather than asking for it again.
if simulating:
self.data = None
else:
self._reread_session_file("could not be read again")
self.params.data_fit = False
self.fit = None
self._refresh_param_fields_from_state()
self._refresh_plots()
self._refresh_diagnostics()
self._update_action_buttons()
self._save_settings()
message = f"Operation mode: {RUN_MODE_LABELS[run_mode]}."
if simulating:
message += " No data is imported; the delay range is set by T_d_min/T_d_max."
self.status_var.set(message)
print(f"bd_fresnel_gui: {message}")
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
@@ -701,7 +804,7 @@ class BDFresnelApp(tk.Tk):
self._update_action_buttons()
self._save_settings()
message = f"Mode: {MODE_LABELS[mode]}."
message = f"Operation 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;"
@@ -714,8 +817,8 @@ class BDFresnelApp(tk.Tk):
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:
throughout, so neither mode must change underneath it."""
for b in self._mode_buttons + self._run_mode_buttons:
b.state(["!disabled"] if enabled else ["disabled"])
def _on_field_change(self, field_name):
@@ -880,17 +983,21 @@ class BDFresnelApp(tk.Tk):
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)
"""Fit needs a data file (it takes its delay range from the
imported scan) and a valid set of beam/material inputs.
Simulate needs only the inputs -- its delay range is entered."""
simulating = self.params.run_mode == RUN_MODE_SIMULATION
ready = (inputs_valid(self.params, require_data=not simulating)
and (simulating or self.data is not None))
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
"""Export writes the plot image and a data table, so it stays
disabled until a fit or simulation has actually completed.
Importing a new file, or changing mode, clears the result and
disables it again."""
ready = self.fit is not None and (
self.params.run_mode == RUN_MODE_SIMULATION or self.data is not None)
self.export_button.config(state="normal" if ready else "disabled")
def _update_action_buttons(self):
@@ -1017,7 +1124,8 @@ class BDFresnelApp(tk.Tk):
# ------------------------------------------------------------------
def _on_fit(self):
if self.data is None:
simulating = self.params.run_mode == RUN_MODE_SIMULATION
if self.data is None and not simulating:
return
self.fit_button.config(state="disabled", text="Processing...")
self.import_button.config(state="disabled")
@@ -1035,8 +1143,12 @@ class BDFresnelApp(tk.Tk):
# 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
# In Simulation mode there is no scan to take the range from:
# T_d_min/T_d_max are the values entered in the panel and are
# left exactly as they are.
if not simulating:
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.
@@ -1063,18 +1175,22 @@ class BDFresnelApp(tk.Tk):
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.fit_button.config(text=self.run_action_label)
self.import_button.config(
state="disabled" if self.params.run_mode == RUN_MODE_SIMULATION else "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.")
done = ("Simulation" if self.params.run_mode == RUN_MODE_SIMULATION
else "Fit")
self.status_var.set(f"{done} complete in {elapsed:.2f} s.")
print(f"bd_fresnel_gui: {done.lower()} 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.fit_button.config(text=self.run_action_label)
self.import_button.config(
state="disabled" if self.params.run_mode == RUN_MODE_SIMULATION else "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.
@@ -1094,8 +1210,14 @@ class BDFresnelApp(tk.Tk):
"""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"]
# Simulation mode has no measurement: the calculated curve
# supplies the delay axis, and there are no markers to size.
simulating = self.data is None
if simulating:
tau_d = tau_d_shifted = self.fit["tau_d"]
else:
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
@@ -1118,10 +1240,15 @@ class BDFresnelApp(tk.Tk):
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:
# Pump probe carries no deflection column, and has no Deflection
# panel to size.
has_deflection = (self.params.mode == MODE_BEAM_DEFLECTION if simulating
else self.data["DeltaEoE"] is not None)
if simulating:
fit_tau_d_disp = self.fit["tau_d"] / scale
T_points = self.fit["T"]
DeltaEoE_points = self.fit["DeltaEoE"] if has_deflection else None
elif 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"]])
@@ -1142,6 +1269,7 @@ class BDFresnelApp(tk.Tk):
return dict(
tau_d_disp=tau_d_disp, fit_tau_d_disp=fit_tau_d_disp, has_fit=has_fit,
has_data=not simulating,
marker_size=marker_size,
T_points=T_points, DeltaEoE_points=DeltaEoE_points,
x_min=x_min, x_max=x_max, scale_label=scale_label,
@@ -1326,7 +1454,9 @@ class BDFresnelApp(tk.Tk):
"""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 [])
handles = [h for h in (data_line, fit_line) if h is not None]
if not handles:
return
ax.legend(handles=handles, labels=[h.get_label() for h in handles],
loc="lower right")
@@ -1356,15 +1486,22 @@ class BDFresnelApp(tk.Tk):
fit_line = None
if ctx["has_fit"]:
# "Simulated" rather than "Fit" when there is no
# measurement it could be a fit to.
fit_line, = ax.plot(ctx["fit_tau_d_disp"], 100 * self.fit[key],
linestyle="-", color=color, label="Fit")
linestyle="-", color=color,
label="Fit" if ctx["has_data"] else "Simulated")
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)
# Simulation mode plots the calculated curve alone -- there is
# no measurement, so no markers and no "Data" legend entry.
data_line = None
if ctx["has_data"]:
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
@@ -1379,7 +1516,12 @@ class BDFresnelApp(tk.Tk):
self._order_legend(ax, data_line, fit_line)
def _refresh_plots(self):
if self.data is None:
# Fitting shows the measurement as soon as it is imported;
# Simulation has nothing to show until it has been run.
if self.data is None and self.fit is None:
for child in self.plot_holder.winfo_children():
child.destroy()
self._plot_view = None
return
fig = self._build_combined_figure()
@@ -1701,11 +1843,15 @@ class BDFresnelApp(tk.Tk):
# ------------------------------------------------------------------
def _on_export(self):
if self.data is None or self.fit is None:
simulating = self.params.run_mode == RUN_MODE_SIMULATION
if self.fit is None or (self.data is None and not simulating):
return
default_name = self.params.filename.replace(".txt", "_fit.txt")
# Simulation has no imported file to name the output after.
default_name = (self.params.filename.replace(".txt", "_fit.txt")
if not simulating else "simulation.txt")
path = filedialog.asksaveasfilename(
title="Select filename for fit export",
title="Select filename for simulation export" if simulating
else "Select filename for fit export",
initialdir=self.params.pathname or os.getcwd(),
initialfile=default_name,
defaultextension=".txt",
@@ -1716,6 +1862,27 @@ class BDFresnelApp(tk.Tk):
return
try:
if simulating:
# Nothing to interpolate onto and no data columns to
# pair with: the calculated signal is written on its
# own delay grid.
if self.params.mode == MODE_PUMP_PROBE:
export_data = np.column_stack([self.fit["tau_d"], self.fit["T"]])
header = "Delay (fs), T (Simulated)"
else:
export_data = np.column_stack([
self.fit["tau_d"], self.fit["DeltaEoE"],
self.fit["T"], self.fit["Delta_n"]])
header = ("Delay (fs), DeltaE / E (Simulated), "
"T (Simulated), Delta_n (simulated)")
np.savetxt(path, export_data, delimiter=",", fmt="%.8g",
header=header, comments="", newline="\r\n")
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()
return
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
@@ -1754,7 +1921,7 @@ class BDFresnelApp(tk.Tk):
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:
if self.data is None and self.fit is None:
return []
# Built fresh here rather than reusing the on-screen figure:
@@ -1849,10 +2016,10 @@ class BDFresnelApp(tk.Tk):
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
bottom: Operation mode -> Data Columns -> 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.
"""
@@ -1861,21 +2028,28 @@ class BDFresnelApp(tk.Tk):
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")
simulating = p.run_mode == RUN_MODE_SIMULATION
# Simulation reads no file, so there is no path and no column
# layout to record.
if not simulating:
lines.append(f"Import data file {p.import_filepath}.\n")
lines.append(f"Operation mode: {MODE_LABELS[p.mode]}, "
f"{RUN_MODE_LABELS[p.run_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")
if not simulating:
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.
# log alone: in Fitting mode T_d_min/T_d_max are derived from
# the imported scan's delay range at fit time, in Simulation
# mode they are entered directly.
lines.append("Simulation Parameters:")
lines.append(f" X_num: {p.X_num}")
lines.append(f" X_max: {p.X_max} w_0")