diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..048cbb6 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,77 @@ +# Changelog + +All notable changes to BD Fresnel are documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). + +## [Unreleased] + +## [2.5] - 2026-09-21 + +### Added + +- **Mode** box, below Data columns: a two-button toggle selecting + **Beam deflection** or **Pump probe**. Beam deflection is the default + and behaves as before. +- Pump probe mode, for measurements with the probe centred on the pump: + - Only the delay and transmission columns are required, so a + two-column scan can be imported. The DeltaEoE column is ignored and + its field disabled. + - `x_0` is fixed at 0 and cannot be edited. + - Only the Transmission plot is displayed and exported. The exported + image is named `_fit_transmission.jpg` / `.svg` and is 3.25 in + wide, a single column. The exported data table holds delay, T (data) + and T (fit). + - The mechanism pull-downs offer the absorptive (NLA) and mixed + (both) mechanisms; a mixed mechanism contributes its absorptive + part. The purely refractive (NLR) mechanisms, which cannot change + the transmission, are excluded. Switching to pump probe empties any + slot holding one; switching back restores it, provided the slot is + still empty. +- The selected mode is saved with the other settings and recorded in the + parameter log. + +### Changed + +- Changing mode discards the current fit, which was computed with the + other mode's settings, and re-reads the imported file under the new + mode's column requirements. A file the new mode cannot use is cleared + with an explanation, and loaded again on switching back. The mode + cannot be changed while a fit runs. + +### Fixed + +- Values such as `nan`, `inf` or `1e999` are rejected in parameter fields. + They previously turned the fit to NaN, and crashed the mechanism + parameters dialog. +- An invalid entry in a numeric field reverts to its previous value, as the + integer fields and the mechanism dialog already did, instead of becoming 0. +- Every parameter change is saved as it is made. Numeric fields, mechanism + choices and the diagnostics option were previously saved only on Import, + Fit, Export or Exit, so a crash lost them. +- Changing a column number or the delimiter re-reads only a file imported in + the current session. Straight after launch it could load the previous + session's file, or report an error about one that had since moved. +- When a file cannot be read with a new column number or delimiter, its data + and fit are cleared. They previously stayed on screen, and could be + exported, under settings that no longer described them. +- The data columns in use must each be different. Two quantities could + previously be read from the same column without any warning. +- The x tick label at the join between the Transmission and Deflection plots + is hidden when it collides with its neighbour. A rounding error let some + such labels through. + +### Changed + +- The source files carry the GPLv3 notice. + +## [2.4] - 2026-09-21 + +First release recorded in this changelog. Earlier history is not documented +here. + +### Fixed + +- README parameter tables corrected to match the program's window: the + default T and DeltaEoE data columns were swapped, and several defaults, + labels and descriptions disagreed with what the interface shows. diff --git a/README.md b/README.md index a0c943a..781c326 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,11 @@ diffraction, and computes the transmission `T` and normalised beam deflection compared against the simulation, and the result exported as data, a log, and publication-sized figures. +Two measurement modes are supported. **Beam deflection** fits both signals. +**Pump probe** is for measurements with the probe centred on the pump, where +there is no deflection: it fits the transmission alone, and needs only delay +and transmission data. + ![BD Fresnel fitting a measured scan](docs/screenshot.png) ## Features @@ -23,6 +28,9 @@ publication-sized figures. - Excited-state absorption via a five-level population model (S₀, S₁, S₂, T₁, T₂) solved through the sample depth for a range of radial irradiances. - Side-by-side transmission and deflection plots with imported data overlaid. +- Beam deflection and pump probe measurement modes. Pump probe reads a + two-column delay/transmission scan, fixes the probe on the pump axis, and + offers only the mechanisms that can change the transmission. - Optional diagnostic figures showing each mechanism's response function before and after convolution, plus the ESA populations and beam transmissions. - Export of the data/fit comparison, a full parameter log, and figures at @@ -57,29 +65,36 @@ right: **Fitting**, **Diagnostics**, and **Parameter log**. A typical session: 1. Set the **Data columns** to match your file, and the delimiter. -2. Press **Import…** and choose a scan. The plots show the measured data. -3. Fill in the beam, material and geometry parameters, and configure one or +2. Choose the **Mode**: Beam deflection or Pump probe. +3. Press **Import…** and choose a scan. The plots show the measured data. +4. Fill in the beam, material and geometry parameters, and configure one or more mechanisms with the **Params…** buttons. -4. Press **Fit** to run the simulation and overlay it on the data. -5. Press **Export…** to write the results. +5. Press **Fit** to run the simulation and overlay it on the data. +6. Press **Export…** to write the results. **Fit** stays disabled until a file is imported, and **Export** until a fit has completed. +Changing the mode, a column number or the delimiter re-reads the imported file. +Any fit is discarded, since it belonged to the previous settings. If the file +cannot be read with the new settings, its data is cleared rather than left on +screen, and it is read again once the settings allow. + Parameters are saved to `last_settings.json` beside the scripts when they change, and restored at the next launch. The data file itself is not restored. ## Input data format -A delimited text file with one header line, then one row per delay point. Three -columns are required; which ones is set in the **Data columns** box, so extra -columns can be present and ignored. +A delimited text file with one header line, then one row per delay point. Beam +deflection needs three columns and pump probe two; which ones is set in the +**Data columns** box, so extra columns can be present and ignored. Each +quantity must come from a different column. -| Quantity | Units | Default column | -| --- | --- | --- | -| `τ_d` | fs | 1 | -| `ΔE/E` | fractional | 2 | -| `T` | fractional (1.0 = no change) | 3 | +| Quantity | Units | Default column | Needed in | +| --- | --- | --- | --- | +| `τ_d` | fs | 1 | both modes | +| `ΔE/E` | fractional | 2 | Beam deflection only | +| `T` | fractional (1.0 = no change) | 3 | both modes | The delimiter field takes a single character, `\t` for a tab, or is left blank to split on any run of whitespace. @@ -95,6 +110,13 @@ to split on any run of whitespace. | `DeltaEoE column` | `2` | Deflection data column | | `Delimiter` | `,` | Data column delimiter character | +### Mode + +| Option | Effect | +|-------------------|-------------------------------------------------| +| `Beam deflection` | Transmission and deflection, offset probe | +| `Pump probe` | Transmission only, centered probe | + ### Simulation parameters | Variable | Default | Column contents | @@ -141,7 +163,7 @@ to split on any run of whitespace. | `n` | `1.4565` | Linear index | | `dndl` | `-0.027158` | First order dispersion (um^-1) | -### System geometry +### Measurement parameters | Variable | Default | Column contents | |----------------|-------------|-----------------------------------| @@ -167,24 +189,31 @@ to split on any run of whitespace. `NLR` denotes a purely refractive response, `NLA` a purely absorptive one, and `both` a mechanism carrying each. +Pump probe offers only the `NLA` and `both` mechanisms: with the probe centred, +a `both` mechanism contributes its absorptive part, and an `NLR` mechanism +cannot change the transmission at all. Switching to Pump probe sets aside any +`NLR` mechanism already chosen; switching back restores it, provided its slot +is still empty. + ## Export output Exporting to `_fit.txt` also writes, in the same directory: | File | Contents | | --- | --- | -| `_fit.txt` | delay, data and fit for `T`, `ΔE/E` and `Δn` | +| `_fit.txt` | delay, data and fit for `T`, `ΔE/E` and `Δn`; in Pump probe, delay and `T` only | | `_fit_log.txt` | every parameter, plus a manifest of the files written | -| `_fit_combined.jpg` / `.svg` | transmission and deflection, 6.5 in at 300 dpi | +| `_fit_combined.jpg` / `.svg` | transmission and deflection, 6.5 in at 300 dpi (Beam deflection) | +| `_fit_transmission.jpg` / `.svg` | transmission only, 3.25 in at 300 dpi (Pump probe) | | `_fit_raw_response.jpg` | each mechanism's `R[t]` and `A[t]` | | `_fit_convolved_response.jpg` | the same after convolution, plus the total | The last two appear only when *Show diagnostic plots during Fit* is ticked. The log records enough to reproduce a run: data columns and delimiter, the -simulation grid, every beam, material and geometry value, each mechanism with -its parameters, and the derived quantities (`n_g`, `T_lin`, `z_0`, `I_0`, -`rho`). +mode, the simulation grid, every beam, material and geometry value, each +mechanism with its parameters, and the derived quantities (`n_g`, `T_lin`, +`z_0`, `I_0`, `rho`). ## Files @@ -225,4 +254,4 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . NumPy, SciPy, Matplotlib and mpmath are all BSD-licensed, so distributing this program -under the GPL alongside them poses no conflict. \ No newline at end of file +under the GPL alongside them poses no conflict. diff --git a/bd_fresnel_core.py b/bd_fresnel_core.py index b9f5c8d..76bdbc8 100644 --- a/bd_fresnel_core.py +++ b/bd_fresnel_core.py @@ -1,5 +1,21 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +# BD Fresnel - physics and parameter model +# +# 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 . """ bd_fresnel_core.py =================== @@ -78,6 +94,8 @@ NOTES ON THE MATLAB -> PYTHON TRANSLATION numpy.heaviside(x, 0.5). """ +__version__ = "2.5" + import time import datetime @@ -155,6 +173,37 @@ MECHANISM_NAMES = [ "Exponential rise/decay (both)", ] +# The empty slot. Its "(both)" suffix is inherited from the original +# app's list and carries no meaning -- it contributes nothing -- so it +# stays selectable in every mode. +NO_MECHANISM = "None (both)" + +# Measurement modes. Beam deflection is the program's original +# behaviour. Pump probe centres the probe on the pump (x_0 = 0), where +# the deflection signal vanishes by symmetry, and so fits transmission +# alone. Only mechanisms with an absorptive part can change the +# transmission, so the purely refractive ones are excluded. +MODE_BEAM_DEFLECTION = "beam_deflection" +MODE_PUMP_PROBE = "pump_probe" +MODES = (MODE_BEAM_DEFLECTION, MODE_PUMP_PROBE) + + +def mechanism_allowed(name: str, mode: str) -> bool: + """Whether a mechanism may occupy a slot in the given mode. Pump + probe admits the absorptive (NLA) and mixed (both) mechanisms, plus + the empty slot, and excludes the purely refractive (NLR) ones. A + mixed mechanism contributes its absorptive part to the transmission; + its refractive part produces no deflection with the probe centred.""" + if mode == MODE_PUMP_PROBE: + return name == NO_MECHANISM or name.endswith(("(NLA)", "(both)")) + return name in MECHANISM_NAMES + + +def mechanism_names_for_mode(mode: str) -> List[str]: + """The mechanism pull-down's choices in the given mode, in the + original list order.""" + return [n for n in MECHANISM_NAMES if mechanism_allowed(n, mode)] + # Per-mechanism (parameter name, unit label) pairs, in order, matching # the param_names/param_units cell arrays in set_params_GUI.m exactly. MECHANISM_PARAM_SPECS = { @@ -281,6 +330,15 @@ class BDFresnelParams: data_imported: bool = False data_fit: bool = False + # --- measurement mode (see set_mode) --- + mode: str = MODE_BEAM_DEFLECTION + # Beam-deflection settings put aside while in pump-probe mode, and + # restored on switching back: the x_0 that pump probe forces to 0, + # and the mechanism slots as they were before the non-absorptive + # ones were cleared. Unused (and the list empty) in beam deflection. + x_0_beam_deflection: float = 0.5 + mech_beam_deflection: List[Mechanism] = field(default_factory=list) + # --- file paths --- filename: str = "" pathname: str = "" @@ -1127,21 +1185,100 @@ def inputs_valid(p: BDFresnelParams) -> bool: # save_settings.m / persistence (JSON in place of MATLAB's .mat file) # ============================================================================= +def _mech_to_dicts(mechs): + return [dict(name=m.name, param=list(m.param)) for m in mechs] + + +def _mech_from_dicts(items): + return [Mechanism(name=m["name"], param=list(m["param"])) for m in items] + + +# Fields holding a list of Mechanism objects, which json cannot +# serialize directly. +_MECHANISM_LIST_FIELDS = ("mech", "mech_beam_deflection") + + def params_to_dict(p: BDFresnelParams) -> dict: d = dict(p.__dict__) - d["mech"] = [dict(name=m.name, param=list(m.param)) for m in p.mech] + for name in _MECHANISM_LIST_FIELDS: + d[name] = _mech_to_dicts(getattr(p, name)) return d def params_from_dict(d: dict) -> BDFresnelParams: d = dict(d) - mech_list = d.pop("mech", None) + mech_lists = {name: d.pop(name, None) for name in _MECHANISM_LIST_FIELDS} p = BDFresnelParams(**{k: v for k, v in d.items() if k in BDFresnelParams.__dataclass_fields__}) - if mech_list: - p.mech = [Mechanism(name=m["name"], param=list(m["param"])) for m in mech_list] + for name, items in mech_lists.items(): + if items: + setattr(p, name, _mech_from_dicts(items)) + apply_mode_constraints(p) return p +def _copy_mech(m: Mechanism) -> Mechanism: + return Mechanism(name=m.name, param=list(m.param)) + + +def apply_mode_constraints(p: BDFresnelParams) -> None: + """Brings p into line with its mode without touching the set-aside + beam-deflection state: an unknown mode falls back to beam + deflection, and pump probe forces x_0 to 0 and empties any slot + holding a mechanism the mode does not allow. Applied to every set + of parameters loaded from disk, so a hand-edited or damaged + settings file cannot put the program in an inconsistent state.""" + if p.mode not in MODES: + p.mode = MODE_BEAM_DEFLECTION + if p.mode == MODE_PUMP_PROBE: + p.x_0 = 0.0 + for i, m in enumerate(p.mech): + if not mechanism_allowed(m.name, p.mode): + p.mech[i] = Mechanism() + + +def set_mode(p: BDFresnelParams, mode: str): + """Switches p to `mode`, returning (cleared, restored): the slot + indices emptied on entering pump probe, and the ones refilled on + leaving it. Both are empty when the mode does not change. + + Entering pump probe sets aside the current x_0 and mechanism slots, + then sets x_0 = 0 and empties every slot the mode does not allow + (the purely refractive ones); the rest stay where they are, + parameters and all. + + Leaving it restores x_0, and puts each cleared mechanism back in + its slot -- but only if that slot is still empty. A slot the user + has since filled keeps its new mechanism, since that is the more + recent choice. Mechanisms edited while in pump probe likewise keep + their edits. + """ + if mode not in MODES: + raise ValueError(f"unknown mode {mode!r}; expected one of {MODES}") + if mode == p.mode: + return [], [] + + cleared, restored = [], [] + if mode == MODE_PUMP_PROBE: + p.x_0_beam_deflection = p.x_0 + p.mech_beam_deflection = [_copy_mech(m) for m in p.mech] + p.mode = mode + p.x_0 = 0.0 + for i, m in enumerate(p.mech): + if not mechanism_allowed(m.name, mode): + p.mech[i] = Mechanism() + cleared.append(i) + else: + p.mode = mode + p.x_0 = p.x_0_beam_deflection + for i, saved in enumerate(p.mech_beam_deflection[:len(p.mech)]): + was_cleared = not mechanism_allowed(saved.name, MODE_PUMP_PROBE) + if was_cleared and p.mech[i].name == NO_MECHANISM: + p.mech[i] = _copy_mech(saved) + restored.append(i) + p.mech_beam_deflection = [] + return cleared, restored + + def save_settings(p: BDFresnelParams, filepath: str) -> None: """JSON equivalent of save_settings.m (which saved handles.params to last_settings.mat).""" diff --git a/bd_fresnel_gui.py b/bd_fresnel_gui.py index 4727905..6d60c8e 100644 --- a/bd_fresnel_gui.py +++ b/bd_fresnel_gui.py @@ -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 . """ 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("<>", 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 "."