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
6 changed files with 1050 additions and 126 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 -23
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
@@ -141,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)."""
+583 -93
View File
File diff suppressed because it is too large Load Diff
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)