Upload files to "/"
This commit is contained in:
+362
-46
@@ -1,5 +1,21 @@
|
||||
#!/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
|
||||
==================
|
||||
@@ -48,6 +64,10 @@ from bd_fresnel_core import (
|
||||
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
|
||||
|
||||
@@ -159,6 +179,20 @@ FIELD_IS_NONNEGATIVE = {
|
||||
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 = [
|
||||
@@ -180,6 +214,7 @@ class LabeledEntry(ttk.Frame):
|
||||
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
|
||||
@@ -229,6 +264,11 @@ class LabeledEntry(ttk.Frame):
|
||||
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)."""
|
||||
@@ -255,6 +295,7 @@ class MechanismRow(ttk.Frame):
|
||||
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):
|
||||
@@ -266,6 +307,10 @@ class MechanismRow(ttk.Frame):
|
||||
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)
|
||||
@@ -312,6 +357,10 @@ class ResizableFigureCanvas:
|
||||
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()
|
||||
@@ -335,6 +384,12 @@ class BDFresnelApp(tk.Tk):
|
||||
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()
|
||||
@@ -494,6 +549,18 @@ 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":
|
||||
@@ -562,14 +629,113 @@ class BDFresnelApp(tk.Tk):
|
||||
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:
|
||||
print(f"bd_fresnel_gui: '{field_name}' must be a real number.")
|
||||
value = 0.0
|
||||
# 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)
|
||||
@@ -584,6 +750,7 @@ class BDFresnelApp(tk.Tk):
|
||||
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
|
||||
@@ -604,8 +771,8 @@ class BDFresnelApp(tk.Tk):
|
||||
widget.set(value)
|
||||
print(f"bd_fresnel_gui: {field_name} updated to {value}.")
|
||||
|
||||
if reread and self.params.import_filepath:
|
||||
self._reload_current_data_file()
|
||||
if reread:
|
||||
self._reread_session_file("cannot be read with these column numbers")
|
||||
self._save_settings()
|
||||
|
||||
def _on_column_change(self, field_name):
|
||||
@@ -628,27 +795,66 @@ class BDFresnelApp(tk.Tk):
|
||||
|
||||
# Same reasoning as a column change: whatever is loaded was
|
||||
# parsed with the old delimiter, so re-read it.
|
||||
if self.params.import_filepath:
|
||||
self._reload_current_data_file()
|
||||
self._reread_session_file("cannot be read with this delimiter")
|
||||
self._save_settings()
|
||||
|
||||
def _reload_current_data_file(self):
|
||||
path = self.params.import_filepath
|
||||
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:
|
||||
messagebox.showerror("File Import Error", f"File: {path} is invalid.\n\n{exc}")
|
||||
return
|
||||
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} with the new column layout.")
|
||||
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]
|
||||
@@ -659,6 +865,7 @@ class BDFresnelApp(tk.Tk):
|
||||
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)
|
||||
@@ -695,9 +902,14 @@ class BDFresnelApp(tk.Tk):
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _read_data_file(self, path) -> dict:
|
||||
"""Reads the delay/deflection/transmission scan at `path`,
|
||||
taking each quantity from the column selected in the "Data
|
||||
columns" box. Raises on a malformed file."""
|
||||
"""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:
|
||||
@@ -706,11 +918,34 @@ class BDFresnelApp(tk.Tk):
|
||||
col_tau_d = self.params.col_tau_d
|
||||
col_T = self.params.col_T
|
||||
col_DeltaEoE = self.params.col_DeltaEoE
|
||||
needed = max(col_tau_d, col_T, 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
|
||||
@@ -726,6 +961,9 @@ class BDFresnelApp(tk.Tk):
|
||||
# 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
|
||||
@@ -744,7 +982,8 @@ class BDFresnelApp(tk.Tk):
|
||||
def _on_import(self):
|
||||
initial_dir = self.params.pathname or os.getcwd()
|
||||
path = filedialog.askopenfilename(
|
||||
title="Import transmission/deflection data",
|
||||
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", "*.*")],
|
||||
)
|
||||
@@ -761,6 +1000,7 @@ class BDFresnelApp(tk.Tk):
|
||||
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
|
||||
@@ -782,6 +1022,7 @@ class BDFresnelApp(tk.Tk):
|
||||
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)
|
||||
|
||||
@@ -824,6 +1065,7 @@ class BDFresnelApp(tk.Tk):
|
||||
|
||||
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.")
|
||||
@@ -833,6 +1075,7 @@ class BDFresnelApp(tk.Tk):
|
||||
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()
|
||||
@@ -875,10 +1118,14 @@ 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:
|
||||
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"]])
|
||||
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"]
|
||||
@@ -915,6 +1162,11 @@ class BDFresnelApp(tk.Tk):
|
||||
# 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
|
||||
|
||||
@@ -971,11 +1223,17 @@ class BDFresnelApp(tk.Tk):
|
||||
# export, where the figure is already at its final printed size).
|
||||
SCREEN_TEXT_BOOST = 1.35
|
||||
|
||||
def _rescale_screen_text(self, fig, axes):
|
||||
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(fig.get_size_inches()[0] / self.SCREEN_FIGSIZE[0]
|
||||
scale = max(width_in / self.SCREEN_FIGSIZE[0]
|
||||
* self.SCREEN_TEXT_BOOST,
|
||||
self.MIN_SCREEN_TEXT_SCALE)
|
||||
rc = self.SCREEN_RC
|
||||
@@ -1033,7 +1291,12 @@ class BDFresnelApp(tk.Tk):
|
||||
ax_left.set_xlim(xlim)
|
||||
fig.draw(renderer)
|
||||
|
||||
lo, hi = min(xlim), max(xlim)
|
||||
# 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())
|
||||
@@ -1126,10 +1389,11 @@ class BDFresnelApp(tk.Tk):
|
||||
self._plot_view = ResizableFigureCanvas(self.plot_holder, fig) # held, see __init__
|
||||
|
||||
def _build_combined_figure(self, figsize=None, print_style=False):
|
||||
"""Builds the single side-by-side figure shown in the plot tab
|
||||
(and saved as the export image): Transmission on the left,
|
||||
Deflection on the right with its y-axis and tick labels moved
|
||||
to the right-hand side.
|
||||
"""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
|
||||
@@ -1140,6 +1404,38 @@ class BDFresnelApp(tk.Tk):
|
||||
|
||||
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")
|
||||
@@ -1151,7 +1447,6 @@ class BDFresnelApp(tk.Tk):
|
||||
# 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.
|
||||
pad = self.EXPORT_LAYOUT_PAD if print_style else self.SCREEN_LAYOUT_PAD
|
||||
|
||||
def relayout(f=fig, a=ax_left, b=ax_right, pad=pad,
|
||||
print_style=print_style):
|
||||
@@ -1422,15 +1717,23 @@ class BDFresnelApp(tk.Tk):
|
||||
|
||||
try:
|
||||
T_interp = np.interp(self.data["tau_d_shifted"], self.fit["tau_d"], self.fit["T"])
|
||||
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"])
|
||||
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)")
|
||||
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")
|
||||
|
||||
@@ -1445,11 +1748,12 @@ class BDFresnelApp(tk.Tk):
|
||||
messagebox.showerror("Export failed", traceback.format_exc().strip().splitlines()[-1])
|
||||
|
||||
def _export_plot_images(self, export_path):
|
||||
"""Saves the combined Transmission (left) / Deflection (right,
|
||||
y-axis on the right) figure as .jpg and .svg alongside the
|
||||
exported data/log files, plus every diagnostic figure as .jpg
|
||||
when the fit was run with diagnostics enabled. Returns the
|
||||
paths written, in the order written."""
|
||||
"""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 []
|
||||
|
||||
@@ -1457,12 +1761,20 @@ class BDFresnelApp(tk.Tk):
|
||||
# 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.
|
||||
width = self.EXPORT_WIDTH_IN
|
||||
height = width * self.SCREEN_FIGSIZE[1] / self.SCREEN_FIGSIZE[0]
|
||||
# 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 (("_combined.jpg", "jpg", self.EXPORT_DPI),
|
||||
("_combined.svg", "svg", None)):
|
||||
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)
|
||||
@@ -1537,7 +1849,7 @@ class BDFresnelApp(tk.Tk):
|
||||
omitted).
|
||||
|
||||
Section order matches the GUI's left-panel field order top to
|
||||
bottom: Data Columns -> Simulation grid (not itself a GUI
|
||||
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
|
||||
@@ -1550,11 +1862,15 @@ class BDFresnelApp(tk.Tk):
|
||||
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}")
|
||||
lines.append(f" DeltaEoE column: {p.col_DeltaEoE}")
|
||||
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
|
||||
@@ -1630,8 +1946,8 @@ class BDFresnelApp(tk.Tk):
|
||||
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 two
|
||||
# combined plots are always written, and one .jpg per
|
||||
# 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 "."
|
||||
|
||||
Reference in New Issue
Block a user