Simulation mode #4

Merged
manuel merged 4 commits from simulation_mode into main 2026-09-30 15:21:50 +00:00
4 changed files with 350 additions and 97 deletions
Showing only changes of commit 38c09a4272 - Show all commits
+40 -4
View File
@@ -6,6 +6,45 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## [Unreleased]
## [2.6] - 2026-09-30
### Added
- **Simulation** run mode: a second toggle in the Operation mode box,
offering **Fitting** and **Simulation**. Fitting is the default and
behaves as before.
- Simulation mode, for computing a signal without a measurement:
- No file is imported. **Import...** and the data column and
delimiter fields are disabled.
- The delay range is entered as `T_d_min` and `T_d_max` (in `tau_p`)
in the Simulation parameters box. In Fitting mode these are taken
from the imported scan and the fields are disabled.
- Only the calculated curves are plotted, without data markers, and
the plot legend reads **Simulated** rather than Fit.
- The **Fit** button is relabelled **Simulate**, and is enabled by
valid parameters alone rather than by an imported file.
- The export holds the calculated signals on their own delay grid,
with no data columns to pair them with. The parameter log omits the
import path and the data column section.
- The mode combines with the measurement mode: Pump probe and
Simulation together give a single Transmission panel and a
two-column table, as Pump probe does when fitting.
- The run mode is saved with the other settings and recorded in the
parameter log.
### Changed
- The **Mode** box is renamed **Operation mode** and moved to the top of
the parameter panel, above Data columns. The parameter log and status
messages use the new name, and the log records both modes on one line.
- Changing run mode discards the current result, which described the
other mode's delay range or a measurement the new mode does not show.
Switching to Simulation sets the imported scan aside and switching
back reloads it. The run mode cannot be changed while a fit runs.
- `inputs_valid` takes a `require_data` argument, so Simulation can
enable its action button without an imported file. Fitting is
unaffected.
## [2.5] - 2026-09-21
### Added
@@ -38,6 +77,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
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.
- The source files carry the GPLv3 notice.
### Fixed
@@ -61,10 +101,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
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
+39 -12
View File
@@ -15,6 +15,10 @@ Two measurement modes are supported. **Beam deflection** fits both signals.
there is no deflection: it fits the transmission alone, and needs only delay
and transmission data.
The program also runs without a measurement. In **Simulation** mode nothing is
imported: the signal is computed from the parameters alone, over a delay range
entered by hand, and only the calculated curves are plotted and exported.
![BD Fresnel fitting a measured scan](docs/screenshot.png)
## Features
@@ -27,10 +31,13 @@ and transmission data.
parameter `rho`.
- 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.
- Side-by-side transmission and deflection plots, with imported data overlaid
when there is any.
- 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.
- Fitting and simulation run modes. Simulation computes the signal with no
data imported, over a delay range entered in the panel.
- 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
@@ -62,18 +69,29 @@ python bd_fresnel_gui.py
The window opens with the parameter panel on the left and three tabs on the
right: **Fitting**, **Diagnostics**, and **Parameter log**.
A typical session:
Fitting a measured scan:
1. Set the **Data columns** to match your file, and the delimiter.
2. Choose the **Mode**: Beam deflection or Pump probe.
1. Under **Operation mode**, choose **Beam deflection** or **Pump probe**, and
leave the second toggle on **Fitting**.
2. Set the **Data columns** to match your file, and the delimiter.
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.
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.
Simulating without a measurement:
1. Under **Operation mode**, choose **Simulation**. **Import…** and the data
column fields are disabled, and **Fit** becomes **Simulate**.
2. Set `T_d_min` and `T_d_max` in **Simulation parameters** to the delay range
to compute over. In Fitting mode these come from the imported file, so they
are editable only here.
3. Fill in the parameters and mechanisms as above.
4. Press **Simulate**, then **Export…**.
**Fit** stays disabled until a file is imported; **Simulate** needs only valid
parameters. **Export** stays disabled until a fit or simulation 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
@@ -110,12 +128,14 @@ to split on any run of whitespace.
| `DeltaEoE column` | `2` | Deflection data column |
| `Delimiter` | `,` | Data column delimiter character |
### Mode
### Operation mode
| Option | Effect |
|-------------------|-------------------------------------------------|
| `Beam deflection` | Transmission and deflection, offset probe |
| `Pump probe` | Transmission only, centered probe |
| `Fitting` | Compare the calculation against an imported scan |
| `Simulation` | Calculate without a scan, over an entered range |
### Simulation parameters
@@ -126,6 +146,8 @@ to split on any run of whitespace.
| `T_num` | `100` | Number of temporal points |
| `T_max` | `5.0` | Range of temporal sampling (tau_p) |
| `T_d_num` | `150` | Number of delay points over range |
| `T_d_min` | `-5.0` | Delay range start (tau_p), Simulation only |
| `T_d_max` | `5.0` | Delay range end (tau_p), Simulation only |
### Excitation beam parameters
@@ -201,7 +223,7 @@ Exporting to `<name>_fit.txt` also writes, in the same directory:
| File | Contents |
| --- | --- |
| `<name>_fit.txt` | delay, data and fit for `T`, `ΔE/E` and `Δn`; in Pump probe, delay and `T` only |
| `<name>_fit.txt` | delay, data and fit for `T`, `ΔE/E` and `Δn`; in Pump probe, delay and `T` only. In Simulation, the calculated signals alone |
| `<name>_fit_log.txt` | every parameter, plus a manifest of the files written |
| `<name>_fit_combined.jpg` / `.svg` | transmission and deflection, 6.5 in at 300 dpi (Beam deflection) |
| `<name>_fit_transmission.jpg` / `.svg` | transmission only, 3.25 in at 300 dpi (Pump probe) |
@@ -210,10 +232,15 @@ Exporting to `<name>_fit.txt` also writes, in the same directory:
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
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`).
In Simulation mode the export is named after the file you choose rather than an
imported scan, and the table holds the calculated signals on their own delay
grid, with no data columns to pair them with.
The log records enough to reproduce a run: both modes, the data columns and
delimiter, the simulation grid including the delay range, every beam, material
and geometry value, each mechanism with its parameters, and the derived
quantities (`n_g`, `T_lin`, `z_0`, `I_0`, `rho`). In Simulation mode the import
path and data column sections are omitted, having nothing to describe.
## Files
+20 -4
View File
@@ -94,7 +94,7 @@ NOTES ON THE MATLAB -> PYTHON TRANSLATION
numpy.heaviside(x, 0.5).
"""
__version__ = "2.5"
__version__ = "2.6"
import time
import datetime
@@ -187,6 +187,15 @@ MODE_BEAM_DEFLECTION = "beam_deflection"
MODE_PUMP_PROBE = "pump_probe"
MODES = (MODE_BEAM_DEFLECTION, MODE_PUMP_PROBE)
# Run modes, independent of the measurement mode above. Fitting is the
# program's original behaviour: a measured scan is imported and the
# calculation compared against it. Simulation imports nothing and
# computes the signal from the parameters alone, over a delay range
# entered by hand rather than taken from a file.
RUN_MODE_FITTING = "fitting"
RUN_MODE_SIMULATION = "simulation"
RUN_MODES = (RUN_MODE_FITTING, RUN_MODE_SIMULATION)
def mechanism_allowed(name: str, mode: str) -> bool:
"""Whether a mechanism may occupy a slot in the given mode. Pump
@@ -332,6 +341,8 @@ class BDFresnelParams:
# --- measurement mode (see set_mode) ---
mode: str = MODE_BEAM_DEFLECTION
# --- run mode: fit an imported scan, or simulate without one ---
run_mode: str = RUN_MODE_FITTING
# 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
@@ -1157,10 +1168,13 @@ def calc_beam_params(p: BDFresnelParams) -> BDFresnelParams:
# inputs_valid.m (nested function inside BD_Fresnel_GUI.m)
# =============================================================================
def inputs_valid(p: BDFresnelParams) -> bool:
def inputs_valid(p: BDFresnelParams, require_data: bool = True) -> bool:
"""Direct port of inputs_valid.m: whether the Fit button should be
enabled. Requires physically sensible beam/material parameters AND
that data has actually been imported."""
that data has actually been imported.
require_data=False drops the last condition, for Simulation mode,
which computes the signal without importing anything."""
return bool(
p.E_p > 0
and p.tau_p_FWHM > 0
@@ -1177,7 +1191,7 @@ def inputs_valid(p: BDFresnelParams) -> bool:
and p.alpha_p >= 0
and p.d > 0
and p.l > 0
and p.data_imported
and (p.data_imported or not require_data)
)
@@ -1229,6 +1243,8 @@ def apply_mode_constraints(p: BDFresnelParams) -> None:
settings file cannot put the program in an inconsistent state."""
if p.mode not in MODES:
p.mode = MODE_BEAM_DEFLECTION
if p.run_mode not in RUN_MODES:
p.run_mode = RUN_MODE_FITTING
if p.mode == MODE_PUMP_PROBE:
p.x_0 = 0.0
for i, m in enumerate(p.mech):
+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")