Compare commits
25
Commits
add_readme
...
d7ab1b823e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d7ab1b823e | ||
|
|
98e95180cc | ||
|
|
38c09a4272 | ||
|
|
cc67401de9 | ||
|
|
6d7996ff30 | ||
|
|
61dbd0452b | ||
|
|
667c37fcb5 | ||
|
|
526185a980 | ||
|
|
f593c3ff07 | ||
|
|
cc5f7622cf | ||
|
|
4c4ec2d1ce | ||
|
|
7cd523b5db | ||
|
|
5d8a132031 | ||
|
|
32f335562f | ||
|
|
a6b56dabe3 | ||
|
|
f3a760bc62 | ||
|
|
81c7c3234c | ||
|
|
1f324d678c | ||
|
|
56430a6202 | ||
|
|
c1187cd846 | ||
|
|
03acb17de4 | ||
|
|
bc06521601 | ||
|
|
6cf2bf4b8a | ||
|
|
cb12b8cfc7 | ||
|
|
67dbda7c19 |
+113
@@ -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.
|
||||
@@ -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
|
||||
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.
|
||||
|
||||

|
||||
|
||||
## Features
|
||||
@@ -22,7 +31,13 @@ publication-sized figures.
|
||||
parameter `rho`.
|
||||
- Excited-state absorption via a five-level population model (S₀, S₁, S₂, T₁,
|
||||
T₂) solved through the sample depth for a range of radial irradiances.
|
||||
- Side-by-side transmission and deflection plots with imported data overlaid.
|
||||
- Side-by-side transmission and deflection plots, with imported data overlaid
|
||||
when there is any.
|
||||
- Beam deflection and pump probe measurement modes. Pump probe reads a
|
||||
two-column delay/transmission scan, fixes the probe on the pump axis, and
|
||||
offers only the mechanisms that can change the transmission.
|
||||
- Fitting and simulation run modes. Simulation computes the signal with no
|
||||
data imported, over a delay range entered in the panel.
|
||||
- Optional diagnostic figures showing each mechanism's response function before
|
||||
and after convolution, plus the ESA populations and beam transmissions.
|
||||
- Export of the data/fit comparison, a full parameter log, and figures at
|
||||
@@ -54,36 +69,131 @@ python bd_fresnel_gui.py
|
||||
The window opens with the parameter panel on the left and three tabs on the
|
||||
right: **Fitting**, **Diagnostics**, and **Parameter log**.
|
||||
|
||||
A typical session:
|
||||
Fitting a measured scan:
|
||||
|
||||
1. Set the **Data columns** to match your file, and the delimiter.
|
||||
2. Press **Import…** and choose a scan. The plots show the measured data.
|
||||
3. Fill in the beam, material and geometry parameters, and configure one or
|
||||
1. Under **Operation mode**, choose **Beam deflection** or **Pump probe**, and
|
||||
leave the second toggle on **Fitting**.
|
||||
2. Set the **Data columns** to match your file, and the delimiter.
|
||||
3. Press **Import…** and choose a scan. The plots show the measured data.
|
||||
4. Fill in the beam, material and geometry parameters, and configure one or
|
||||
more mechanisms with the **Params…** buttons.
|
||||
4. Press **Fit** to run the simulation and overlay it on the data.
|
||||
5. Press **Export…** to write the results.
|
||||
5. Press **Fit** to run the simulation and overlay it on the data.
|
||||
6. Press **Export…** to write the results.
|
||||
|
||||
**Fit** stays disabled until a file is imported, and **Export** until a fit has
|
||||
completed.
|
||||
Simulating without a measurement:
|
||||
|
||||
1. Under **Operation mode**, choose **Simulation**. **Import…** and the data
|
||||
column fields are disabled, and **Fit** becomes **Simulate**.
|
||||
2. Set `T_d_min` and `T_d_max` in **Simulation parameters** to the delay range
|
||||
to compute over. In Fitting mode these come from the imported file, so they
|
||||
are editable only here.
|
||||
3. Fill in the parameters and mechanisms as above.
|
||||
4. Press **Simulate**, then **Export…**.
|
||||
|
||||
**Fit** stays disabled until a file is imported; **Simulate** needs only valid
|
||||
parameters. **Export** stays disabled until a fit or simulation has completed.
|
||||
|
||||
Changing the mode, a column number or the delimiter re-reads the imported file.
|
||||
Any fit is discarded, since it belonged to the previous settings. If the file
|
||||
cannot be read with the new settings, its data is cleared rather than left on
|
||||
screen, and it is read again once the settings allow.
|
||||
|
||||
Parameters are saved to `last_settings.json` beside the scripts when they
|
||||
change, and restored at the next launch. The data file itself is not restored.
|
||||
|
||||
## Input data format
|
||||
|
||||
A delimited text file with one header line, then one row per delay point. Three
|
||||
columns are required; which ones is set in the **Data columns** box, so extra
|
||||
columns can be present and ignored.
|
||||
A delimited text file with one header line, then one row per delay point. Beam
|
||||
deflection needs three columns and pump probe two; which ones is set in the
|
||||
**Data columns** box, so extra columns can be present and ignored. Each
|
||||
quantity must come from a different column.
|
||||
|
||||
| Quantity | Units | Default column |
|
||||
| --- | --- | --- |
|
||||
| Delay `τ_d` | fs | 1 |
|
||||
| `ΔE/E` | fractional | 2 |
|
||||
| `T` | fractional (1.0 = no change) | 3 |
|
||||
| Quantity | Units | Default column | Needed in |
|
||||
| --- | --- | --- | --- |
|
||||
| `τ_d` | fs | 1 | both modes |
|
||||
| `ΔE/E` | fractional | 2 | Beam deflection only |
|
||||
| `T` | fractional (1.0 = no change) | 3 | both modes |
|
||||
|
||||
The delimiter field takes a single character, `\t` for a tab, or is left blank
|
||||
to split on any run of whitespace.
|
||||
|
||||
## 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
|
||||
|
||||
| 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
|
||||
`both` a mechanism carrying each.
|
||||
|
||||
Pump probe offers only the `NLA` and `both` mechanisms: with the probe centred,
|
||||
a `both` mechanism contributes its absorptive part, and an `NLR` mechanism
|
||||
cannot change the transmission at all. Switching to Pump probe sets aside any
|
||||
`NLR` mechanism already chosen; switching back restores it, provided its slot
|
||||
is still empty.
|
||||
|
||||
## Export output
|
||||
|
||||
Exporting to `<name>_fit.txt` also writes, in the same directory:
|
||||
|
||||
| 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_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_convolved_response.jpg` | the same after convolution, plus the total |
|
||||
|
||||
The last two appear only when *Show diagnostic plots during Fit* is ticked.
|
||||
|
||||
The log records enough to reproduce a run: data columns and delimiter, the
|
||||
simulation grid, every beam, material and geometry value, each mechanism with
|
||||
its parameters, and the derived quantities (`n_g`, `T_lin`, `z_0`, `I_0`,
|
||||
`rho`).
|
||||
In Simulation mode the export is named after the file you choose rather than an
|
||||
imported scan, and the table holds the calculated signals on their own delay
|
||||
grid, with no data columns to pair them with.
|
||||
|
||||
The log records enough to reproduce a run: both modes, the data columns and
|
||||
delimiter, the simulation grid including the delay range, every beam, material
|
||||
and geometry value, each mechanism with its parameters, and the derived
|
||||
quantities (`n_g`, `T_lin`, `z_0`, `I_0`, `rho`). In Simulation mode the import
|
||||
path and data column sections are omitted, having nothing to describe.
|
||||
|
||||
## Files
|
||||
|
||||
@@ -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. |
|
||||
| `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
|
||||
|
||||
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
|
||||
polarization resolved ultrafast nonlinear refraction." *Opt. Lett.*
|
||||
**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
@@ -1,5 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# BD Fresnel - physics and parameter model
|
||||
#
|
||||
# Copyright (C) 2019-2026 Manuel R. Ferdinandus
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
"""
|
||||
bd_fresnel_core.py
|
||||
===================
|
||||
@@ -78,6 +94,8 @@ NOTES ON THE MATLAB -> PYTHON TRANSLATION
|
||||
numpy.heaviside(x, 0.5).
|
||||
"""
|
||||
|
||||
__version__ = "2.6"
|
||||
|
||||
import time
|
||||
import datetime
|
||||
|
||||
@@ -155,6 +173,46 @@ MECHANISM_NAMES = [
|
||||
"Exponential rise/decay (both)",
|
||||
]
|
||||
|
||||
# The empty slot. Its "(both)" suffix is inherited from the original
|
||||
# app's list and carries no meaning -- it contributes nothing -- so it
|
||||
# stays selectable in every mode.
|
||||
NO_MECHANISM = "None (both)"
|
||||
|
||||
# Measurement modes. Beam deflection is the program's original
|
||||
# behaviour. Pump probe centres the probe on the pump (x_0 = 0), where
|
||||
# the deflection signal vanishes by symmetry, and so fits transmission
|
||||
# alone. Only mechanisms with an absorptive part can change the
|
||||
# transmission, so the purely refractive ones are excluded.
|
||||
MODE_BEAM_DEFLECTION = "beam_deflection"
|
||||
MODE_PUMP_PROBE = "pump_probe"
|
||||
MODES = (MODE_BEAM_DEFLECTION, MODE_PUMP_PROBE)
|
||||
|
||||
# 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
|
||||
# the param_names/param_units cell arrays in set_params_GUI.m exactly.
|
||||
MECHANISM_PARAM_SPECS = {
|
||||
@@ -281,6 +339,17 @@ class BDFresnelParams:
|
||||
data_imported: 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 ---
|
||||
filename: str = ""
|
||||
pathname: str = ""
|
||||
@@ -1099,10 +1168,13 @@ def calc_beam_params(p: BDFresnelParams) -> BDFresnelParams:
|
||||
# inputs_valid.m (nested function inside BD_Fresnel_GUI.m)
|
||||
# =============================================================================
|
||||
|
||||
def inputs_valid(p: BDFresnelParams) -> bool:
|
||||
def inputs_valid(p: BDFresnelParams, require_data: bool = True) -> bool:
|
||||
"""Direct port of inputs_valid.m: whether the Fit button should be
|
||||
enabled. Requires physically sensible beam/material parameters AND
|
||||
that data has actually been imported."""
|
||||
that data has actually been imported.
|
||||
|
||||
require_data=False drops the last condition, for Simulation mode,
|
||||
which computes the signal without importing anything."""
|
||||
return bool(
|
||||
p.E_p > 0
|
||||
and p.tau_p_FWHM > 0
|
||||
@@ -1119,7 +1191,7 @@ def inputs_valid(p: BDFresnelParams) -> bool:
|
||||
and p.alpha_p >= 0
|
||||
and p.d > 0
|
||||
and p.l > 0
|
||||
and p.data_imported
|
||||
and (p.data_imported or not require_data)
|
||||
)
|
||||
|
||||
|
||||
@@ -1127,21 +1199,102 @@ def inputs_valid(p: BDFresnelParams) -> bool:
|
||||
# save_settings.m / persistence (JSON in place of MATLAB's .mat file)
|
||||
# =============================================================================
|
||||
|
||||
def _mech_to_dicts(mechs):
|
||||
return [dict(name=m.name, param=list(m.param)) for m in mechs]
|
||||
|
||||
|
||||
def _mech_from_dicts(items):
|
||||
return [Mechanism(name=m["name"], param=list(m["param"])) for m in items]
|
||||
|
||||
|
||||
# Fields holding a list of Mechanism objects, which json cannot
|
||||
# serialize directly.
|
||||
_MECHANISM_LIST_FIELDS = ("mech", "mech_beam_deflection")
|
||||
|
||||
|
||||
def params_to_dict(p: BDFresnelParams) -> dict:
|
||||
d = dict(p.__dict__)
|
||||
d["mech"] = [dict(name=m.name, param=list(m.param)) for m in p.mech]
|
||||
for name in _MECHANISM_LIST_FIELDS:
|
||||
d[name] = _mech_to_dicts(getattr(p, name))
|
||||
return d
|
||||
|
||||
|
||||
def params_from_dict(d: dict) -> BDFresnelParams:
|
||||
d = dict(d)
|
||||
mech_list = d.pop("mech", None)
|
||||
mech_lists = {name: d.pop(name, None) for name in _MECHANISM_LIST_FIELDS}
|
||||
p = BDFresnelParams(**{k: v for k, v in d.items() if k in BDFresnelParams.__dataclass_fields__})
|
||||
if mech_list:
|
||||
p.mech = [Mechanism(name=m["name"], param=list(m["param"])) for m in mech_list]
|
||||
for name, items in mech_lists.items():
|
||||
if items:
|
||||
setattr(p, name, _mech_from_dicts(items))
|
||||
apply_mode_constraints(p)
|
||||
return p
|
||||
|
||||
|
||||
def _copy_mech(m: Mechanism) -> Mechanism:
|
||||
return Mechanism(name=m.name, param=list(m.param))
|
||||
|
||||
|
||||
def apply_mode_constraints(p: BDFresnelParams) -> None:
|
||||
"""Brings p into line with its mode without touching the set-aside
|
||||
beam-deflection state: an unknown mode falls back to beam
|
||||
deflection, and pump probe forces x_0 to 0 and empties any slot
|
||||
holding a mechanism the mode does not allow. Applied to every set
|
||||
of parameters loaded from disk, so a hand-edited or damaged
|
||||
settings file cannot put the program in an inconsistent state."""
|
||||
if p.mode not in MODES:
|
||||
p.mode = MODE_BEAM_DEFLECTION
|
||||
if p.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:
|
||||
"""JSON equivalent of save_settings.m (which saved handles.params
|
||||
to last_settings.mat)."""
|
||||
|
||||
+583
-93
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
@@ -1,5 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- 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
|
||||
=====================
|
||||
@@ -39,6 +55,7 @@ Usage:
|
||||
previous_mechanism=old_mech)
|
||||
"""
|
||||
|
||||
import math
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
|
||||
@@ -102,6 +119,16 @@ class SetParamsDialog(tk.Toplevel):
|
||||
if self._entries and self._entries[0] is not None:
|
||||
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
|
||||
def _format(value: float) -> str:
|
||||
# MATLAB's num2str-equivalent-enough default formatting.
|
||||
@@ -114,10 +141,10 @@ class SetParamsDialog(tk.Toplevel):
|
||||
if var is None:
|
||||
return
|
||||
try:
|
||||
value = float(var.get())
|
||||
value = self._parse(var.get())
|
||||
except ValueError:
|
||||
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]
|
||||
self._last_valid[idx] = value
|
||||
var.set(self._format(value))
|
||||
@@ -128,7 +155,7 @@ class SetParamsDialog(tk.Toplevel):
|
||||
if var is None:
|
||||
continue
|
||||
try:
|
||||
values[i] = float(var.get())
|
||||
values[i] = self._parse(var.get())
|
||||
except ValueError:
|
||||
values[i] = self._last_valid[i]
|
||||
self.result = Mechanism(name=self.mechanism_name, param=values)
|
||||
|
||||
Reference in New Issue
Block a user