Author SHA1 Message Date
manuel 98e95180cc Upload files to "/" 2026-09-30 15:20:45 +00:00
manuel 38c09a4272 Upload files to "/" 2026-09-30 15:20:31 +00:00
manuel cc67401de9 Upload files to "docs" 2026-09-30 15:19:54 +00:00
manuel 6d7996ff30 Upload files to "docs" 2026-09-30 15:17:57 +00:00
manuel 61dbd0452b Merge pull request 'Pump probe mode' (#3) from pump_probe_mode into main
Reviewed-on: #3
2026-09-23 01:20:45 +00:00
manuel 667c37fcb5 Upload files to "/" 2026-09-23 01:18:42 +00:00
manuel 526185a980 Upload files to "docs" 2026-09-23 01:16:41 +00:00
manuel f593c3ff07 Upload files to "/" 2026-09-23 01:16:19 +00:00
manuel cc5f7622cf Upload files to "/" 2026-09-23 01:15:43 +00:00
manuel 4c4ec2d1ce Update README.md 2026-09-21 22:55:59 +00:00
manuel 7cd523b5db Update README.md 2026-09-21 13:32:39 +00:00
manuel 5d8a132031 Update README.md 2026-09-21 13:29:26 +00:00
manuel 32f335562f Update README.md 2026-09-21 13:27:22 +00:00
manuel a6b56dabe3 Update README.md 2026-09-21 13:18:15 +00:00
manuel f3a760bc62 Update README.md 2026-09-21 13:10:46 +00:00
manuel 81c7c3234c Update README.md 2026-09-21 11:41:15 +00:00
manuel 1f324d678c Update README.md 2026-09-21 11:40:34 +00:00
manuel 56430a6202 Update README.md 2026-09-21 11:38:27 +00:00
manuel c1187cd846 Update README.md 2026-09-21 11:37:42 +00:00
manuel 03acb17de4 Update README.md 2026-09-21 11:36:44 +00:00
manuel bc06521601 Update README.md 2026-09-17 16:37:00 +00:00
manuel 6cf2bf4b8a Merge pull request 'Update README.md' (#2) from remove_port_notes into main
Reviewed-on: #2
2026-09-12 20:30:47 +00:00
manuel cb12b8cfc7 Update README.md 2026-09-12 20:30:39 +00:00
manuel 67dbda7c19 Merge pull request 'Add readme' (#1) from add_readme into main
Reviewed-on: #1
2026-09-12 20:27:44 +00:00
6 changed files with 1050 additions and 148 deletions
+113
View File
@@ -0,0 +1,113 @@
# 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.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
- **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 `<name>_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.
- The source files carry the GPLv3 notice.
### 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.
## [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.
+164 -45
View File
@@ -10,6 +10,15 @@ diffraction, and computes the transmission `T` and normalised beam deflection
compared against the simulation, and the result exported as data, a log, and compared against the simulation, and the result exported as data, a log, and
publication-sized figures. 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.
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) ![BD Fresnel fitting a measured scan](docs/screenshot.png)
## Features ## Features
@@ -22,7 +31,13 @@ publication-sized figures.
parameter `rho`. parameter `rho`.
- Excited-state absorption via a five-level population model (S₀, S₁, S₂, T₁, - 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. 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 - Optional diagnostic figures showing each mechanism's response function before
and after convolution, plus the ESA populations and beam transmissions. and after convolution, plus the ESA populations and beam transmissions.
- Export of the data/fit comparison, a full parameter log, and figures at - Export of the data/fit comparison, a full parameter log, and figures at
@@ -54,36 +69,131 @@ python bd_fresnel_gui.py
The window opens with the parameter panel on the left and three tabs on the The window opens with the parameter panel on the left and three tabs on the
right: **Fitting**, **Diagnostics**, and **Parameter log**. 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. 1. Under **Operation mode**, choose **Beam deflection** or **Pump probe**, and
2. Press **Import…** and choose a scan. The plots show the measured data. leave the second toggle on **Fitting**.
3. Fill in the beam, material and geometry parameters, and configure one or 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. more mechanisms with the **Params…** buttons.
4. Press **Fit** to run the simulation and overlay it on the data. 5. Press **Fit** to run the simulation and overlay it on the data.
5. Press **Export…** to write the results. 6. Press **Export…** to write the results.
**Fit** stays disabled until a file is imported, and **Export** until a fit has Simulating without a measurement:
completed.
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
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 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. change, and restored at the next launch. The data file itself is not restored.
## Input data format ## Input data format
A delimited text file with one header line, then one row per delay point. Three A delimited text file with one header line, then one row per delay point. Beam
columns are required; which ones is set in the **Data columns** box, so extra deflection needs three columns and pump probe two; which ones is set in the
columns can be present and ignored. **Data columns** box, so extra columns can be present and ignored. Each
quantity must come from a different column.
| Quantity | Units | Default column | | Quantity | Units | Default column | Needed in |
| --- | --- | --- | | --- | --- | --- | --- |
| Delay `τ_d` | fs | 1 | | `τ_d` | fs | 1 | both modes |
| `ΔE/E` | fractional | 2 | | `ΔE/E` | fractional | 2 | Beam deflection only |
| `T` | fractional (1.0 = no change) | 3 | | `T` | fractional (1.0 = no change) | 3 | both modes |
The delimiter field takes a single character, `\t` for a tab, or is left blank The delimiter field takes a single character, `\t` for a tab, or is left blank
to split on any run of whitespace. to split on any run of whitespace.
## Parameters
### Data columns (1-indexed)
| Variable | Default | Column contents |
|-------------------|---------|---------------------------------------|
| `tau_d column` | `1` | Delay column (fs) |
| `T column` | `3` | Transmission data column |
| `DeltaEoE column` | `2` | Deflection data column |
| `Delimiter` | `,` | Data column delimiter character |
### 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
| Variable | Default | Column contents |
|----------------|---------|---------------------------------------|
| `X_num` | `50` | Number of spatial points |
| `X_max` | `5.0` | Range of spatial sampling (w_0) |
| `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
| Variable | Default | Column contents |
|----------------|---------|---------------------------------------|
| `E_p` | `1.36` | Excitation pulse energy (uJ) |
| `tau_p_FWHM` | `55.0` | Excitation pulse duration (fs) |
| `w_0p` | `246.0` | Excitation beam waist (um) |
| `lambda_p` | `800.0` | Excitation pulse wavelength (nm) |
### Probe beam parameters
| Variable | Default | Column contents |
|----------------|---------|---------------------------------------|
| `tau_FWHM` | `60.0` | Probe pulse duration (fs) |
| `w_0` | `43.0` | Probe beam waist (um) |
| `lambda` | `650.0` | Probe pulse wavelength (nm) |
### Material parameters at excitation wavelength
| Variable | Default | Column contents |
|----------------|-------------|-----------------------------------|
| `R_p` | `0.0` | Reflectivity |
| `alpha_p` | `0.0` | Linear absorption (cm^-1) |
| `n_p` | `1.4533` | Linear index |
| `dndl_p` | `-0.017284` | First order dispersion (um^-1) |
| `alpha_2d` | `0.0` | 2 photon absorption (e-11 m/W) |
### Material parameters at probe wavelength
| Variable | Default | Column contents |
|----------------|-------------|-----------------------------------|
| `R` | `0.0` | Reflectivity |
| `alpha` | `0.0` | Linear absorption (cm^-1) |
| `n` | `1.4565` | Linear index |
| `dndl` | `-0.027158` | First order dispersion (um^-1) |
### Measurement parameters
| Variable | Default | Column contents |
|----------------|-------------|-----------------------------------|
| `l` | `1.0` | Sample thickness (mm) |
| `d` | `15.0` | Distance to detector (cm) |
| `shift` | `0.0` | Temporal shift (fs) |
| `x_0` | `0.5` | Displacement of probe (w_0p) |
## Mechanisms ## Mechanisms
| Mechanism | Parameters | | Mechanism | Parameters |
@@ -101,24 +211,36 @@ to split on any run of whitespace.
`NLR` denotes a purely refractive response, `NLA` a purely absorptive one, and `NLR` denotes a purely refractive response, `NLA` a purely absorptive one, and
`both` a mechanism carrying each. `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 ## Export output
Exporting to `<name>_fit.txt` also writes, in the same directory: Exporting to `<name>_fit.txt` also writes, in the same directory:
| File | Contents | | File | Contents |
| --- | --- | | --- | --- |
| `<name>_fit.txt` | delay, data and fit for `T`, `ΔE/E` and `Δn` | | `<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_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 | | `<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) |
| `<name>_fit_raw_response.jpg` | each mechanism's `R[t]` and `A[t]` | | `<name>_fit_raw_response.jpg` | each mechanism's `R[t]` and `A[t]` |
| `<name>_fit_convolved_response.jpg` | the same after convolution, plus the total | | `<name>_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 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 In Simulation mode the export is named after the file you choose rather than an
simulation grid, every beam, material and geometry value, each mechanism with imported scan, and the table holds the calculated signals on their own delay
its parameters, and the derived quantities (`n_g`, `T_lin`, `z_0`, `I_0`, grid, with no data columns to pair them with.
`rho`).
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 ## Files
@@ -128,28 +250,6 @@ its parameters, and the derived quantities (`n_g`, `T_lin`, `z_0`, `I_0`,
| `bd_fresnel_gui.py` | Tkinter interface, plotting, import/export, logging. Entry point. | | `bd_fresnel_gui.py` | Tkinter interface, plotting, import/export, logging. Entry point. |
| `set_params_dialog.py` | modal dialog for entering one mechanism's parameters. | | `set_params_dialog.py` | modal dialog for entering one mechanism's parameters. |
## Notes on the port
The translation follows the MATLAB closely, including its array axis order, so
that intermediate results can be compared directly. Places where this port
deliberately differs are commented at the point of departure. The substantive
ones:
- **Physical constants** are taken from `scipy.constants` rather than
transcribed. The original hard-coded `c = 299797548` in `calc_beam_params`, a
digit transposition of the correct value used elsewhere in the same codebase,
and truncated Planck's constant to seven figures. Correcting the former
shifts `rho` by about 1.7 × 10⁻⁵ relative.
- **Delay-frame consistency**: the delay grid is derived from the shifted
`τ_d`, matching what the plots and export compare against. The original used
the unshifted values, a mismatch whenever `shift ≠ 0`.
- **Diagnostic instantaneous response**: the original's diagnostic plot used
`n_2e` where its four physics branches all used `2·n_2e`, so the plotted
electronic curve was half the simulated one. The plot now matches the
simulation.
- **Dialog close**: closing the parameter dialog with the window button is
treated as OK. In the original it left the caller's `uiwait` blocked forever.
## References ## References
Please cite the following when using results from this program. Please cite the following when using results from this program.
@@ -163,3 +263,22 @@ Please cite the following when using results from this program.
3. Ferdinandus, M. R., et al. (2013). "Beam deflection measurement of time and 3. Ferdinandus, M. R., et al. (2013). "Beam deflection measurement of time and
polarization resolved ultrafast nonlinear refraction." *Opt. Lett.* polarization resolved ultrafast nonlinear refraction." *Opt. Lett.*
**38**(18): 3518–3521. **38**(18): 3518–3521.
## License
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/>.
NumPy, SciPy, Matplotlib and mpmath are all BSD-licensed, so distributing this program
under the GPL alongside them poses no conflict.
+160 -7
View File
@@ -1,5 +1,21 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- 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 <https://www.gnu.org/licenses/>.
""" """
bd_fresnel_core.py bd_fresnel_core.py
=================== ===================
@@ -78,6 +94,8 @@ NOTES ON THE MATLAB -> PYTHON TRANSLATION
numpy.heaviside(x, 0.5). numpy.heaviside(x, 0.5).
""" """
__version__ = "2.6"
import time import time
import datetime import datetime
@@ -155,6 +173,46 @@ MECHANISM_NAMES = [
"Exponential rise/decay (both)", "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)
# 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
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 # Per-mechanism (parameter name, unit label) pairs, in order, matching
# the param_names/param_units cell arrays in set_params_GUI.m exactly. # the param_names/param_units cell arrays in set_params_GUI.m exactly.
MECHANISM_PARAM_SPECS = { MECHANISM_PARAM_SPECS = {
@@ -281,6 +339,17 @@ class BDFresnelParams:
data_imported: bool = False data_imported: bool = False
data_fit: bool = False data_fit: bool = False
# --- 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
# 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 --- # --- file paths ---
filename: str = "" filename: str = ""
pathname: str = "" pathname: str = ""
@@ -1099,10 +1168,13 @@ def calc_beam_params(p: BDFresnelParams) -> BDFresnelParams:
# inputs_valid.m (nested function inside BD_Fresnel_GUI.m) # 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 """Direct port of inputs_valid.m: whether the Fit button should be
enabled. Requires physically sensible beam/material parameters AND 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( return bool(
p.E_p > 0 p.E_p > 0
and p.tau_p_FWHM > 0 and p.tau_p_FWHM > 0
@@ -1119,7 +1191,7 @@ def inputs_valid(p: BDFresnelParams) -> bool:
and p.alpha_p >= 0 and p.alpha_p >= 0
and p.d > 0 and p.d > 0
and p.l > 0 and p.l > 0
and p.data_imported and (p.data_imported or not require_data)
) )
@@ -1127,21 +1199,102 @@ def inputs_valid(p: BDFresnelParams) -> bool:
# save_settings.m / persistence (JSON in place of MATLAB's .mat file) # 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: def params_to_dict(p: BDFresnelParams) -> dict:
d = dict(p.__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 return d
def params_from_dict(d: dict) -> BDFresnelParams: def params_from_dict(d: dict) -> BDFresnelParams:
d = dict(d) 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__}) p = BDFresnelParams(**{k: v for k, v in d.items() if k in BDFresnelParams.__dataclass_fields__})
if mech_list: for name, items in mech_lists.items():
p.mech = [Mechanism(name=m["name"], param=list(m["param"])) for m in mech_list] if items:
setattr(p, name, _mech_from_dicts(items))
apply_mode_constraints(p)
return 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.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):
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: def save_settings(p: BDFresnelParams, filepath: str) -> None:
"""JSON equivalent of save_settings.m (which saved handles.params """JSON equivalent of save_settings.m (which saved handles.params
to last_settings.mat).""" to last_settings.mat)."""
+558 -68
View File
@@ -1,5 +1,21 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- 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 bd_fresnel_gui.py
================== ==================
@@ -48,6 +64,12 @@ from bd_fresnel_core import (
BD_Fresnel_func_ni, BD_Fresnel_func_ni,
save_settings, save_settings,
load_settings, load_settings,
MODE_BEAM_DEFLECTION,
MODE_PUMP_PROBE,
RUN_MODE_FITTING,
RUN_MODE_SIMULATION,
mechanism_names_for_mode,
set_mode,
) )
from set_params_dialog import open_set_params_dialog from set_params_dialog import open_set_params_dialog
@@ -128,14 +150,17 @@ def describe_delimiter(text: str) -> str:
# The simulation grid, in the order shown in the "Simulation # The simulation grid, in the order shown in the "Simulation
# parameters" box: (attribute, label, unit, kind). Integer fields are # parameters" box: (attribute, label, unit, kind). Integer fields are
# counts and must be >= 1; the float fields are extents and cannot be # 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 # negative. T_d_min/T_d_max are signed and are entered only in
# from the imported scan's delay range, not entered. # Simulation mode; in Fitting mode they are taken from the imported
# scan's delay range and the fields are disabled.
SIM_FIELDS = [ SIM_FIELDS = [
("X_num", "X_num (spatial pts)", "points", "int"), ("X_num", "X_num (spatial pts)", "points", "int"),
("X_max", "X_max (spatial extent)", "w_0", "float"), ("X_max", "X_max (spatial extent)", "w_0", "float"),
("T_num", "T_num (time pts)", "points", "int"), ("T_num", "T_num (time pts)", "points", "int"),
("T_max", "T_max (time extent)", "tau_p", "float"), ("T_max", "T_max (time extent)", "tau_p", "float"),
("T_d_num", "T_d_num (delay pts)", "points", "int"), ("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 # The numeric parameter boxes, in panel order. Each entry is
@@ -157,7 +182,31 @@ FIELD_IS_NONNEGATIVE = {
for name, _label, _unit, nonneg in fields for name, _label, _unit, nonneg in fields
} }
FIELD_IS_NONNEGATIVE.update( 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
distinct from other read errors because it is a normal intermediate
state while swapping two column numbers, one field at a time."""
# 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"),
(MODE_PUMP_PROBE, "Pump probe"),
]
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 # Which column of the imported file feeds each quantity. 1-based, in
# the order they are shown in the "Data columns" box. # the order they are shown in the "Data columns" box.
@@ -180,6 +229,7 @@ class LabeledEntry(ttk.Frame):
self.var = tk.StringVar(value=str(value)) self.var = tk.StringVar(value=str(value))
entry = ttk.Entry(self, textvariable=self.var, width=width) entry = ttk.Entry(self, textvariable=self.var, width=width)
entry.pack(side="left") entry.pack(side="left")
self.entry = entry
if integer: if integer:
# Refuse anything but digits at the keystroke level, so a # Refuse anything but digits at the keystroke level, so a
# sign, decimal point or letter can never be typed in the # sign, decimal point or letter can never be typed in the
@@ -229,6 +279,11 @@ class LabeledEntry(ttk.Frame):
def set(self, value): def set(self, value):
self.var.set(str(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): class LabeledStatic(ttk.Frame):
"""Read-only calculated-value display (e.g. rho, I_0_p).""" """Read-only calculated-value display (e.g. rho, I_0_p)."""
@@ -255,6 +310,7 @@ class MechanismRow(ttk.Frame):
state="readonly", width=26) state="readonly", width=26)
combo.pack(side="left", padx=(0, 4)) combo.pack(side="left", padx=(0, 4))
combo.bind("<<ComboboxSelected>>", self._on_selected) combo.bind("<<ComboboxSelected>>", self._on_selected)
self.combo = combo
ttk.Button(self, text="Params...", width=9, command=self._on_params_button).pack(side="left") ttk.Button(self, text="Params...", width=9, command=self._on_params_button).pack(side="left")
def _on_selected(self, event=None): def _on_selected(self, event=None):
@@ -266,6 +322,10 @@ class MechanismRow(ttk.Frame):
def set_name(self, name): def set_name(self, name):
self.mech_var.set(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): def add_section(parent, title):
frame = ttk.LabelFrame(parent, text=title, padding=8) frame = ttk.LabelFrame(parent, text=title, padding=8)
@@ -312,6 +372,10 @@ class ResizableFigureCanvas:
self.widget.place(x=x, y=y, width=new_w, height=new_h) 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) 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) relayout = getattr(self.fig, "_bd_relayout", None)
if relayout is not None: if relayout is not None:
relayout() relayout()
@@ -335,6 +399,12 @@ class BDFresnelApp(tk.Tk):
self.params = self._load_or_default_params() self.params = self._load_or_default_params()
self.data = None # dict with tau_d, tau_d_shifted, T, DeltaEoE, Delta_n self.data = None # dict with tau_d, tau_d_shifted, T, DeltaEoE, Delta_n
self.fit = None # dict, output of BD_Fresnel_func_ni 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._mechanism_rows = []
self._build_layout() self._build_layout()
@@ -482,6 +552,19 @@ class BDFresnelApp(tk.Tk):
def _build_param_fields(self, parent): def _build_param_fields(self, parent):
self._field_widgets = {} 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") sec = add_section(parent, "Data columns")
for name, label in DATA_COLUMN_FIELDS: for name, label in DATA_COLUMN_FIELDS:
w = LabeledEntry(sec, label, getattr(self.params, name), width=6, w = LabeledEntry(sec, label, getattr(self.params, name), width=6,
@@ -496,7 +579,14 @@ class BDFresnelApp(tk.Tk):
sec = add_section(parent, "Simulation parameters") sec = add_section(parent, "Simulation parameters")
for name, label, unit, kind in SIM_FIELDS: 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), w = LabeledEntry(sec, label, getattr(self.params, name),
width=6, unit=unit, integer=True, width=6, unit=unit, integer=True,
on_change=lambda n=name: self._on_int_field_change(n)) on_change=lambda n=name: self._on_int_field_change(n))
@@ -562,14 +652,193 @@ class BDFresnelApp(tk.Tk):
self.diagnostics_var.set(self.params.diagnostics) self.diagnostics_var.set(self.params.diagnostics)
if self.params.filename: if self.params.filename:
self.filename_var.set(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 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)
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 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.
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")])
@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
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"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;"
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 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): def _on_field_change(self, field_name):
widget = self._field_widgets[field_name] widget = self._field_widgets[field_name]
previous = getattr(self.params, field_name)
try: try:
value = widget.get() 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: except ValueError:
print(f"bd_fresnel_gui: '{field_name}' must be a real number.") # Reverted, like the integer fields and the mechanism
value = 0.0 # 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]: if FIELD_IS_NONNEGATIVE[field_name]:
value = abs(value) value = abs(value)
setattr(self.params, field_name, value) setattr(self.params, field_name, value)
@@ -584,6 +853,7 @@ class BDFresnelApp(tk.Tk):
self._refresh_plots() self._refresh_plots()
self._update_fit_button_state() self._update_fit_button_state()
self._save_settings()
def _on_int_field_change(self, field_name, reread=False): def _on_int_field_change(self, field_name, reread=False):
"""Shared handler for the positive-integer inputs: the data """Shared handler for the positive-integer inputs: the data
@@ -604,8 +874,8 @@ class BDFresnelApp(tk.Tk):
widget.set(value) widget.set(value)
print(f"bd_fresnel_gui: {field_name} updated to {value}.") print(f"bd_fresnel_gui: {field_name} updated to {value}.")
if reread and self.params.import_filepath: if reread:
self._reload_current_data_file() self._reread_session_file("cannot be read with these column numbers")
self._save_settings() self._save_settings()
def _on_column_change(self, field_name): def _on_column_change(self, field_name):
@@ -628,27 +898,66 @@ class BDFresnelApp(tk.Tk):
# Same reasoning as a column change: whatever is loaded was # Same reasoning as a column change: whatever is loaded was
# parsed with the old delimiter, so re-read it. # parsed with the old delimiter, so re-read it.
if self.params.import_filepath: self._reread_session_file("cannot be read with this delimiter")
self._reload_current_data_file()
self._save_settings() self._save_settings()
def _reload_current_data_file(self): def _reread_session_file(self, failure_note):
path = self.params.import_filepath """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: try:
data = self._read_data_file(path) 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: except Exception as exc:
messagebox.showerror("File Import Error", f"File: {path} is invalid.\n\n{exc}") self._clear_loaded_data()
return 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.data = data
self.params.data_fit = False self.params.data_fit = False
self.fit = None self.fit = None
self._refresh_plots() self._refresh_plots()
self._refresh_diagnostics() self._refresh_diagnostics()
self._update_action_buttons() 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): def _on_diagnostics_change(self):
self.params.diagnostics = self.diagnostics_var.get() self.params.diagnostics = self.diagnostics_var.get()
self._save_settings()
def _on_mechanism_change(self, index, mechanism_name, reopen_dialog=False): def _on_mechanism_change(self, index, mechanism_name, reopen_dialog=False):
previous = self.params.mech[index] previous = self.params.mech[index]
@@ -659,6 +968,7 @@ class BDFresnelApp(tk.Tk):
else: else:
self.params.mech[index] = Mechanism(name=mechanism_name) self.params.mech[index] = Mechanism(name=mechanism_name)
self._mechanism_rows[index].set_name(self.params.mech[index].name) self._mechanism_rows[index].set_name(self.params.mech[index].name)
self._save_settings()
def _recalc_beam_params(self, refresh_display=False): def _recalc_beam_params(self, refresh_display=False):
calc_beam_params(self.params) calc_beam_params(self.params)
@@ -673,17 +983,21 @@ class BDFresnelApp(tk.Tk):
self.calc_rho.set(f"{self.params.rho:.3f}") self.calc_rho.set(f"{self.params.rho:.3f}")
def _update_fit_button_state(self): def _update_fit_button_state(self):
"""Fit needs both a data file (it takes its delay range from """Fit needs a data file (it takes its delay range from the
the imported scan) and a valid set of beam/material inputs.""" imported scan) and a valid set of beam/material inputs.
ready = self.data is not None and inputs_valid(self.params) 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") self.fit_button.config(state="normal" if ready else "disabled")
def _update_export_button_state(self): def _update_export_button_state(self):
"""Export writes the data/fit comparison table and the plot """Export writes the plot image and a data table, so it stays
image, so it stays disabled until a fit has actually disabled until a fit or simulation has actually completed.
completed. Importing a new file clears the fit and disables it Importing a new file, or changing mode, clears the result and
again.""" disables it again."""
ready = self.data is not None and self.fit is not None 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") self.export_button.config(state="normal" if ready else "disabled")
def _update_action_buttons(self): def _update_action_buttons(self):
@@ -695,9 +1009,14 @@ class BDFresnelApp(tk.Tk):
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def _read_data_file(self, path) -> dict: def _read_data_file(self, path) -> dict:
"""Reads the delay/deflection/transmission scan at `path`, """Reads the scan at `path`, taking each quantity from the
taking each quantity from the column selected in the "Data column selected in the "Data columns" box. Raises on a
columns" box. Raises on a malformed file.""" 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, raw = np.genfromtxt(path, skip_header=1,
delimiter=resolve_delimiter(self.params.delimiter)) delimiter=resolve_delimiter(self.params.delimiter))
if raw.ndim == 1: if raw.ndim == 1:
@@ -706,11 +1025,34 @@ class BDFresnelApp(tk.Tk):
col_tau_d = self.params.col_tau_d col_tau_d = self.params.col_tau_d
col_T = self.params.col_T col_T = self.params.col_T
col_DeltaEoE = self.params.col_DeltaEoE col_DeltaEoE = self.params.col_DeltaEoE
pump_probe = self.params.mode == MODE_PUMP_PROBE
# Every quantity must come from its own column; nothing else
# stops T and DeltaE/E being read from the same one.
used = {"tau_d": col_tau_d, "T": col_T}
if not pump_probe:
used["DeltaEoE"] = col_DeltaEoE
by_column = {}
for name, col in used.items():
by_column.setdefault(col, []).append(name)
clashes = [names for names in by_column.values() if len(names) > 1]
if clashes:
detail = "; ".join(f"{' and '.join(n)} are both column {used[n[0]]}"
for n in clashes)
raise ColumnConflict(f"Each data column must be different: {detail}")
if pump_probe:
needed = max(col_tau_d, col_T)
else:
needed = max(col_tau_d, col_T, col_DeltaEoE) needed = max(col_tau_d, col_T, col_DeltaEoE)
if raw.shape[1] < needed: if raw.shape[1] < needed:
raise ValueError( raise ValueError(
f"file has {raw.shape[1]} column(s), but the selected " f"file has {raw.shape[1]} column(s), but the selected "
f"column numbers need at least {needed}") 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(): if np.isnan(raw).any():
# A delimiter that does not match the file is the usual # A delimiter that does not match the file is the usual
# cause: every line then parses as one unsplittable field # cause: every line then parses as one unsplittable field
@@ -726,6 +1068,9 @@ class BDFresnelApp(tk.Tk):
# 1-based in the GUI, 0-based into the array. # 1-based in the GUI, 0-based into the array.
tau_d = raw[:, col_tau_d - 1] tau_d = raw[:, col_tau_d - 1]
T = raw[:, col_T - 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] DeltaEoE = raw[:, col_DeltaEoE - 1]
lambda_ = self.params.lambda_ * 1e-9 lambda_ = self.params.lambda_ * 1e-9
@@ -744,7 +1089,8 @@ class BDFresnelApp(tk.Tk):
def _on_import(self): def _on_import(self):
initial_dir = self.params.pathname or os.getcwd() initial_dir = self.params.pathname or os.getcwd()
path = filedialog.askopenfilename( 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, initialdir=initial_dir,
filetypes=[("Text files", "*.txt"), ("All files", "*.*")], filetypes=[("Text files", "*.txt"), ("All files", "*.*")],
) )
@@ -761,6 +1107,7 @@ class BDFresnelApp(tk.Tk):
self.params.pathname = os.path.dirname(path) + os.sep self.params.pathname = os.path.dirname(path) + os.sep
self.params.filename = os.path.basename(path) self.params.filename = os.path.basename(path)
self.params.import_filepath = path self.params.import_filepath = path
self._session_data_path = path
self.params.data_imported = True self.params.data_imported = True
self.params.data_fit = False self.params.data_fit = False
self.fit = None self.fit = None
@@ -777,11 +1124,13 @@ class BDFresnelApp(tk.Tk):
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def _on_fit(self): 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 return
self.fit_button.config(state="disabled", text="Processing...") self.fit_button.config(state="disabled", text="Processing...")
self.import_button.config(state="disabled") self.import_button.config(state="disabled")
self.export_button.config(state="disabled") self.export_button.config(state="disabled")
self._set_mode_buttons_enabled(False)
self.status_var.set("Running simulation...") self.status_var.set("Running simulation...")
self.progress.start(12) self.progress.start(12)
@@ -794,6 +1143,10 @@ class BDFresnelApp(tk.Tk):
# since refresh_plots.m/pb_Export_Callback.m both compare # since refresh_plots.m/pb_Export_Callback.m both compare
# against the shifted values. This is a deliberate correction, # against the shifted values. This is a deliberate correction,
# not a faithfulness gap.) # not a faithfulness gap.)
# 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_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 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 # T_d_num is no longer forced here -- it is an input in the
@@ -822,17 +1175,23 @@ class BDFresnelApp(tk.Tk):
self.log_text.delete("1.0", "end") self.log_text.delete("1.0", "end")
self.log_text.insert("1.0", self._build_log_text()) self.log_text.insert("1.0", self._build_log_text())
self.fit_button.config(text="Fit") self.fit_button.config(text=self.run_action_label)
self.import_button.config(state="normal") 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._update_action_buttons()
self.progress.stop() self.progress.stop()
self.status_var.set(f"Fit complete in {elapsed:.2f} s.") done = ("Simulation" if self.params.run_mode == RUN_MODE_SIMULATION
print(f"bd_fresnel_gui: fitting complete. Elapsed time: {elapsed:.2f} s.") 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() self._save_settings()
def _on_fit_error(self, tb_text): def _on_fit_error(self, tb_text):
self.fit_button.config(text="Fit") self.fit_button.config(text=self.run_action_label)
self.import_button.config(state="normal") 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 # Export stays available only if an earlier fit succeeded and
# is still on screen; _update_export_button_state decides. # is still on screen; _update_export_button_state decides.
self._update_action_buttons() self._update_action_buttons()
@@ -851,6 +1210,12 @@ class BDFresnelApp(tk.Tk):
"""Computes the data/fit arrays, axis scale, and shared axis """Computes the data/fit arrays, axis scale, and shared axis
ranges used by every plot (the two live tabs and the combined ranges used by every plot (the two live tabs and the combined
export image), so they all stay perfectly consistent.""" export image), so they all stay perfectly consistent."""
# 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 = self.data["tau_d"]
tau_d_shifted = self.data["tau_d_shifted"] tau_d_shifted = self.data["tau_d_shifted"]
n_pts = len(tau_d) n_pts = len(tau_d)
@@ -875,10 +1240,19 @@ class BDFresnelApp(tk.Tk):
tau_d_disp = tau_d_shifted / scale tau_d_disp = tau_d_shifted / scale
has_fit = self.fit is not None and self.params.data_fit has_fit = self.fit is not None and self.params.data_fit
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 fit_tau_d_disp = self.fit["tau_d"] / scale
T_points = np.concatenate([self.data["T"], self.fit["T"]]) 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: else:
fit_tau_d_disp = None fit_tau_d_disp = None
T_points = self.data["T"] T_points = self.data["T"]
@@ -895,6 +1269,7 @@ class BDFresnelApp(tk.Tk):
return dict( return dict(
tau_d_disp=tau_d_disp, fit_tau_d_disp=fit_tau_d_disp, has_fit=has_fit, 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, marker_size=marker_size,
T_points=T_points, DeltaEoE_points=DeltaEoE_points, T_points=T_points, DeltaEoE_points=DeltaEoE_points,
x_min=x_min, x_max=x_max, scale_label=scale_label, x_min=x_min, x_max=x_max, scale_label=scale_label,
@@ -915,6 +1290,11 @@ class BDFresnelApp(tk.Tk):
# is a full text-column width on US Letter with 1 in margins. The # is a full text-column width on US Letter with 1 in margins. The
# export height keeps the on-screen aspect ratio. # export height keeps the on-screen aspect ratio.
SCREEN_FIGSIZE = (12.0, 5.0) 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_WIDTH_IN = 6.5
EXPORT_DPI = 300 EXPORT_DPI = 300
@@ -971,11 +1351,17 @@ class BDFresnelApp(tk.Tk):
# export, where the figure is already at its final printed size). # export, where the figure is already at its final printed size).
SCREEN_TEXT_BOOST = 1.35 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 # Floor applied last, so it is a true minimum: folding the
# boost in afterwards would raise the effective floor and let # boost in afterwards would raise the effective floor and let
# a very small window clip again. # 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.SCREEN_TEXT_BOOST,
self.MIN_SCREEN_TEXT_SCALE) self.MIN_SCREEN_TEXT_SCALE)
rc = self.SCREEN_RC rc = self.SCREEN_RC
@@ -1033,7 +1419,12 @@ class BDFresnelApp(tk.Tk):
ax_left.set_xlim(xlim) ax_left.set_xlim(xlim)
fig.draw(renderer) 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) right_boxes = [t.get_window_extent(renderer)
for loc, t in zip(ax_right.get_xticks(), for loc, t in zip(ax_right.get_xticks(),
ax_right.get_xticklabels()) ax_right.get_xticklabels())
@@ -1063,7 +1454,9 @@ class BDFresnelApp(tk.Tk):
"""Legend entries listed as Data over Fit, independent of the """Legend entries listed as Data over Fit, independent of the
order the artists were drawn in (the fit is plotted first so order the artists were drawn in (the fit is plotted first so
the data markers sit on top of it).""" 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], ax.legend(handles=handles, labels=[h.get_label() for h in handles],
loc="lower right") loc="lower right")
@@ -1093,10 +1486,17 @@ class BDFresnelApp(tk.Tk):
fit_line = None fit_line = None
if ctx["has_fit"]: 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], 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_on(True)
fit_line.set_clip_path(ax.patch) fit_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], data_line, = ax.plot(ctx["tau_d_disp"], 100 * self.data[key],
linestyle="none", marker="o", color=color, linestyle="none", marker="o", color=color,
markeredgewidth=0, markeredgewidth=0,
@@ -1116,7 +1516,12 @@ class BDFresnelApp(tk.Tk):
self._order_legend(ax, data_line, fit_line) self._order_legend(ax, data_line, fit_line)
def _refresh_plots(self): 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 return
fig = self._build_combined_figure() fig = self._build_combined_figure()
@@ -1126,10 +1531,11 @@ class BDFresnelApp(tk.Tk):
self._plot_view = ResizableFigureCanvas(self.plot_holder, fig) # held, see __init__ self._plot_view = ResizableFigureCanvas(self.plot_holder, fig) # held, see __init__
def _build_combined_figure(self, figsize=None, print_style=False): def _build_combined_figure(self, figsize=None, print_style=False):
"""Builds the single side-by-side figure shown in the plot tab """Builds the figure shown in the plot tab (and saved as the
(and saved as the export image): Transmission on the left, export image). In beam-deflection mode it is side by side:
Deflection on the right with its y-axis and tick labels moved Transmission on the left, Deflection on the right with its
to the right-hand side. 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 `figsize` and `print_style` both default to the on-screen
settings; export passes the smaller print pair. The context is settings; export passes the smaller print pair. The context is
@@ -1140,6 +1546,38 @@ class BDFresnelApp(tk.Tk):
with matplotlib.rc_context(self.PRINT_RC if print_style else self.SCREEN_RC): with matplotlib.rc_context(self.PRINT_RC if print_style else self.SCREEN_RC):
ctx = self._get_plot_context() 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) fig = Figure(figsize=figsize or self.SCREEN_FIGSIZE)
ax_left, ax_right = fig.subplots(1, 2) ax_left, ax_right = fig.subplots(1, 2)
self._plot_signal_axis(ax_left, ctx, "T") self._plot_signal_axis(ax_left, ctx, "T")
@@ -1151,7 +1589,6 @@ class BDFresnelApp(tk.Tk):
# the right. The x tick labels do collide at the join, # the right. The x tick labels do collide at the join,
# though, and that is dealt with after layout, once the # though, and that is dealt with after layout, once the
# labels have their final positions. # 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, def relayout(f=fig, a=ax_left, b=ax_right, pad=pad,
print_style=print_style): print_style=print_style):
@@ -1406,11 +1843,15 @@ class BDFresnelApp(tk.Tk):
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def _on_export(self): 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 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( 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(), initialdir=self.params.pathname or os.getcwd(),
initialfile=default_name, initialfile=default_name,
defaultextension=".txt", defaultextension=".txt",
@@ -1421,7 +1862,36 @@ class BDFresnelApp(tk.Tk):
return return
try: 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"]) T_interp = np.interp(self.data["tau_d_shifted"], self.fit["tau_d"], self.fit["T"])
if self.params.mode == MODE_PUMP_PROBE:
# No deflection was imported, so none is exported: the
# fitted deflection would be identically zero anyway,
# with the probe centred on the pump.
export_data = np.column_stack([
self.data["tau_d_shifted"], self.data["T"], T_interp])
header = "Delay (fs), T (Data), T (Fit)"
else:
DeltaEoE_interp = np.interp(self.data["tau_d_shifted"], self.fit["tau_d"], self.fit["DeltaEoE"]) 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"]) Delta_n_interp = np.interp(self.data["tau_d_shifted"], self.fit["tau_d"], self.fit["Delta_n"])
@@ -1445,24 +1915,33 @@ class BDFresnelApp(tk.Tk):
messagebox.showerror("Export failed", traceback.format_exc().strip().splitlines()[-1]) messagebox.showerror("Export failed", traceback.format_exc().strip().splitlines()[-1])
def _export_plot_images(self, export_path): def _export_plot_images(self, export_path):
"""Saves the combined Transmission (left) / Deflection (right, """Saves the fit figure as .jpg and .svg alongside the exported
y-axis on the right) figure as .jpg and .svg alongside the data/log files -- side by side as "_combined" in beam
exported data/log files, plus every diagnostic figure as .jpg deflection, the Transmission panel alone as "_transmission" in
when the fit was run with diagnostics enabled. Returns the pump probe -- plus every diagnostic figure as .jpg when the fit
paths written, in the order written.""" was run with diagnostics enabled. Returns the paths written, in
if self.data is None: the order written."""
if self.data is None and self.fit is None:
return [] return []
# Built fresh here rather than reusing the on-screen figure: # Built fresh here rather than reusing the on-screen figure:
# the displayed one is a different size and gets resized again # the displayed one is a different size and gets resized again
# by ResizableFigureCanvas as the window changes, so its layout # by ResizableFigureCanvas as the window changes, so its layout
# is both wrong for print and potentially stale. # is both wrong for print and potentially stale.
width = self.EXPORT_WIDTH_IN # Pump probe exports its lone Transmission panel at half the
height = width * self.SCREEN_FIGSIZE[1] / self.SCREEN_FIGSIZE[0] # 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) fig = self._build_combined_figure(figsize=(width, height), print_style=True)
written = [] written = []
for suffix, fmt, dpi in (("_combined.jpg", "jpg", self.EXPORT_DPI), for suffix, fmt, dpi in ((f"{stem}.jpg", "jpg", self.EXPORT_DPI),
("_combined.svg", "svg", None)): (f"{stem}.svg", "svg", None)):
path = self._sibling_path(export_path, suffix) path = self._sibling_path(export_path, suffix)
fig.savefig(path, format=fmt, **({"dpi": dpi} if dpi else {})) fig.savefig(path, format=fmt, **({"dpi": dpi} if dpi else {}))
written.append(path) written.append(path)
@@ -1537,10 +2016,10 @@ class BDFresnelApp(tk.Tk):
omitted). omitted).
Section order matches the GUI's left-panel field order top to Section order matches the GUI's left-panel field order top to
bottom: Data Columns -> Simulation grid (not itself a GUI bottom: Operation mode -> Data Columns -> Simulation grid (not
field, kept as a preamble) -> Pump (Excitation) Beam -> Probe itself a GUI field, kept as a preamble) -> Pump (Excitation)
Beam -> Material @ Pump Wavelength -> Material @ Probe Beam -> Probe Beam -> Material @ Pump Wavelength -> Material @
Wavelength -> System Geometry -> Mechanisms -> Calculated Probe Wavelength -> System Geometry -> Mechanisms -> Calculated
Parameters (probe) -> Calculated Parameters (pump) -> Other Parameters (probe) -> Calculated Parameters (pump) -> Other
(rho). The column numbers are 1-based, as entered in the GUI. (rho). The column numbers are 1-based, as entered in the GUI.
""" """
@@ -1549,17 +2028,28 @@ class BDFresnelApp(tk.Tk):
p = self.params p = self.params
lines = [] lines = []
lines.append(f"{datetime.datetime.now()}: Begin beam deflection program (bd_fresnel_gui.py).\n") lines.append(f"{datetime.datetime.now()}: Begin beam deflection program (bd_fresnel_gui.py).\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"Import data file {p.import_filepath}.\n")
lines.append(f"Operation mode: {MODE_LABELS[p.mode]}, "
f"{RUN_MODE_LABELS[p.run_mode]}\n")
if not simulating:
lines.append("Data Columns:") lines.append("Data Columns:")
lines.append(f" tau_d column: {p.col_tau_d}") lines.append(f" tau_d column: {p.col_tau_d}")
lines.append(f" T column: {p.col_T}") 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" DeltaEoE column: {p.col_DeltaEoE}")
lines.append(f" Delimiter: {describe_delimiter(p.delimiter)}\n") lines.append(f" Delimiter: {describe_delimiter(p.delimiter)}\n")
# The delay grid is included so a run is reproducible from the # 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 # log alone: in Fitting mode T_d_min/T_d_max are derived from
# the imported scan's delay range at fit time. # the imported scan's delay range at fit time, in Simulation
# mode they are entered directly.
lines.append("Simulation Parameters:") lines.append("Simulation Parameters:")
lines.append(f" X_num: {p.X_num}") lines.append(f" X_num: {p.X_num}")
lines.append(f" X_max: {p.X_max} w_0") lines.append(f" X_max: {p.X_max} w_0")
@@ -1630,8 +2120,8 @@ class BDFresnelApp(tk.Tk):
if exported_files: if exported_files:
# Every file this export run produced. They all land in one # Every file this export run produced. They all land in one
# directory, so that is named once in the header and the # directory, so that is named once in the header and the
# entries are bare filenames. The count varies: the two # entries are bare filenames. The count varies: the fit
# combined plots are always written, and one .jpg per # figure's .jpg and .svg are always written, and one .jpg per
# diagnostic figure is added when the fit was run with # diagnostic figure is added when the fit was run with
# diagnostics enabled. # diagnostics enabled.
directory = os.path.dirname(exported_files[0]) or "." directory = os.path.dirname(exported_files[0]) or "."
Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

After

Width:  |  Height:  |  Size: 127 KiB

+30 -3
View File
@@ -1,5 +1,21 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# BD Fresnel - mechanism parameter dialog
#
# 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/>.
""" """
set_params_dialog.py set_params_dialog.py
===================== =====================
@@ -39,6 +55,7 @@ Usage:
previous_mechanism=old_mech) previous_mechanism=old_mech)
""" """
import math
import tkinter as tk import tkinter as tk
from tkinter import ttk from tkinter import ttk
@@ -102,6 +119,16 @@ class SetParamsDialog(tk.Toplevel):
if self._entries and self._entries[0] is not None: if self._entries and self._entries[0] is not None:
self.after(10, self._entries[0].focus_set) self.after(10, self._entries[0].focus_set)
@staticmethod
def _parse(text: str) -> float:
"""float(), but rejecting what it accepts and no parameter can
take: "nan", "inf", and overflows such as "1e999". Letting those
through also crashed _format, which calls int() on the value."""
value = float(text)
if not math.isfinite(value):
raise ValueError(f"{text!r} is not finite")
return value
@staticmethod @staticmethod
def _format(value: float) -> str: def _format(value: float) -> str:
# MATLAB's num2str-equivalent-enough default formatting. # MATLAB's num2str-equivalent-enough default formatting.
@@ -114,10 +141,10 @@ class SetParamsDialog(tk.Toplevel):
if var is None: if var is None:
return return
try: try:
value = float(var.get()) value = self._parse(var.get())
except ValueError: except ValueError:
name = MECHANISM_PARAM_SPECS[self.mechanism_name][idx][0] name = MECHANISM_PARAM_SPECS[self.mechanism_name][idx][0]
print(f"set_params_dialog: '{name}' must be a real number; reverting.") print(f"set_params_dialog: '{name}' must be a finite real number; reverting.")
value = self._last_valid[idx] value = self._last_valid[idx]
self._last_valid[idx] = value self._last_valid[idx] = value
var.set(self._format(value)) var.set(self._format(value))
@@ -128,7 +155,7 @@ class SetParamsDialog(tk.Toplevel):
if var is None: if var is None:
continue continue
try: try:
values[i] = float(var.get()) values[i] = self._parse(var.get())
except ValueError: except ValueError:
values[i] = self._last_valid[i] values[i] = self._last_valid[i]
self.result = Mechanism(name=self.mechanism_name, param=values) self.result = Mechanism(name=self.mechanism_name, param=values)