Files
ZScan_beam_simulation_GUI/README.md
T
2026-09-24 01:31:32 +00:00

327 lines
15 KiB
Markdown

# Z-Scan Beam Simulation
[![License: GPLv3](docs/license-gplv3.svg)](LICENSE)
A desktop application for fitting **Z-scan** measurements of nonlinear optical
materials. It loads raw open-aperture (OA) and closed-aperture (CA) scan data,
applies reference-channel correction and baseline normalization, simulates the
expected transmittance from a set of nonlinear coefficients, and fits those
coefficients to the measurement.
The Z-scan technique measures nonlinear refraction and absorption by translating
a thin sample through the focus of a pulsed laser beam and recording transmitted
energy as a function of position. This program models the beam propagating
through the sample and on to a far-field aperture, and refines the nonlinear
coefficients until the simulated curves match the measured ones.
The method follows Ferdinandus *et al.*, *Measuring small solute nonlinearities
in solution by dual-arm Z-Scan technique* ([FiO 2012, paper
FM4I.6](https://doi.org/10.1364/FIO.2012.FM4I.6)) — see
[Citing this work](#citing-this-work).
![Fit results with measured data](docs/fit_results.png)
## Features
- **Two operation modes.** *Fitting* imports a measured scan and compares the
simulation with it. *Simulation* calculates and displays the signals with no
data at all, over a z range you specify.
- **Load raw scan files** with configurable 1-indexed column mapping, so data
from different acquisition setups can be read without editing the file. A
header row is skipped. Leaving the delimiter blank splits on whitespace,
which covers tab- and space-separated exports; set it explicitly (`,`) for
CSV.
- **Reference-channel correction** to divide out shot-to-shot laser fluctuation,
plus an optional frequency channel.
- **Baseline normalization** by a linear fit through the wings of the scan,
where the sample is far from focus and the response should be flat. The
fraction of points taken from each end is adjustable.
- **Nonlinear refraction and absorption to third order**: n₂, n₃, n₄ and
α₂, α₃, α₄.
- **Full beam simulation**: Gaussian beam with M² correction, temporal pulse
integration, radial propagation to the aperture, and both open- and
closed-aperture transmittance.
- **Automatic fitting** — tick any subset of the six nonlinear coefficients and
refine them by Nelder-Mead simplex against the measured curves.
- **Fit quality reporting**: chi-square per curve, peak-to-valley comparisons
between data and fit, and a propagated uncertainty estimate from the energy,
spot-size and pulse-width errors.
- **Export** the fit, a full parameter log, and publication-ready plots.
- **Settings persistence** — every field is saved on exit and restored on the
next launch.
## Screenshots
The left panel holds every processing and physical parameter; results appear in
three tabs — the referenced/normalized input data, the fit, and a log of all
parameters and fit-quality numbers.
**Referenced / normalized data.** Raw and reference-corrected traces with the
baseline fit drawn over them. The correction visibly removes laser fluctuation
from both channels.
![Reference plot](docs/reference.png)
**Log.** Every parameter that produced the fit, plus the fit-quality numbers.
![Log tab](docs/log.png)
## Installation
Requires Python 3.8+ and:
```
numpy
scipy
matplotlib
```
Tkinter ships with most Python installs. On some Linux distributions it is a
separate package:
```bash
sudo apt install python3-tk # Debian / Ubuntu
sudo dnf install python3-tkinter # Fedora
```
Then:
```bash
pip install numpy scipy matplotlib
python zscan_gui.py
```
## Usage
1. **Choose the Operation Mode** — *Fitting* (the default) or *Simulation*.
The steps below describe Fitting; for Simulation see
[Simulation mode](#simulation-mode).
2. **Browse** to a scan file and set the column numbers for position, CA, OA and
the reference channel. Columns are 1-indexed, matching how they are usually
numbered in acquisition software.
3. **Import.** The Referenced / Normalized tab shows the raw and corrected
traces with the baseline fit drawn over them, so you can confirm the columns
and flags are right before simulating. Changing a column or a processing flag
re-reads the file and redraws immediately.
4. **Enter the measurement parameters** — pulse energy, wavelength, beam waist,
pulse width, sample thickness and refractive index, aperture transmittance.
5. **Run Simulation** to overlay the simulated curves on the data.
6. **Refine Fit** — tick the coefficients to vary and let the optimizer adjust
them. It runs in the background with a live iteration count.
7. **Export** to write the fit data, log and images next to the input file.
### Simulation mode
Selecting **Simulation** calculates the signals without any measurement. Every
input that describes a data file is switched off — the Data File, Data Columns
and Processing Flags boxes, along with **Import**, **Refine Fit**, **Max
iterations** and the Referenced / Normalized tab — and **Run Simulation**
becomes available with nothing imported.
The scan's extent is not measured but stated: **z range (sim.)** sets the
half-width in Rayleigh ranges *z₀* either side of focus (default 15). The
Fit Results panels show the simulated curves alone, padded by 5% above and
below, and the log reports the simulated peak-to-valley values in place of the
data-versus-fit comparison and chi-squares.
**Show CA (else OA/CA)** stays available, since it selects which curve the
right-hand panel draws and both are simulated. Ticking it repeats the run so
the plot follows immediately.
Anything already imported is kept while you work in Simulation, so switching
back to Fitting does not mean importing again. Switching either way clears the
results on screen, which belonged to the other mode.
### Exported files
Written alongside the input file, with an optional extra label in the name. In
Simulation mode there is no input file to name them from, so **Export** asks
where to write; the CSV then holds the simulated curves and no reference figure
is produced:
| File | Contents |
|---|---|
| `<name>_fit.<ext>` | CSV of position, data and fit for the OA, CA and CA/OA curves; in Simulation, position and the simulated OA, CA and CA/OA |
| `<name>_fit_log.txt` | Every parameter, fit-quality metric and output path |
| `<name>_fit.jpg` / `.svg` | Fit figure, raster and vector |
| `<name>_fit_ref.jpg` / `.svg` | Referenced/normalized figure (Fitting only) |
## Project structure
The program is split so the physics can be used without the interface:
- **`zscan_core.py`** — the simulation engine. No GUI or pyplot state; figures
are built as `matplotlib.figure.Figure` objects so any front end can embed
them. Import it directly to drive the simulation from a script or notebook:
```python
from dataclasses import replace
from zscan_core import load_settings, load_and_normalize_data, run_simulation
cfg = replace(load_settings("last_settings.json"), import_filepath="scan.txt")
DATA, norm_OA, norm_CA = load_and_normalize_data(cfg)
results = run_simulation(cfg, DATA)
print(results["OA_chi_square"], results["deltaOAcomp"])
```
Every parameter lives in a single `ZScanConfig` dataclass, which serializes to
and from JSON, so a fit is fully reproducible from its settings file.
- **`zscan_gui.py`** — the Tkinter interface. Simulation and fitting run on
background threads so the window stays responsive, and plots rescale with it.
## Parameters
### Operation mode
| Option | Effect |
|--------------|-----------------------------------------------------------------|
| `Fitting` | Default. Imports a scan and compares the simulation with it. |
| `Simulation` | No data: the calculated signals are shown alone, over `z range (sim.)`. The data-file inputs, Import, Refine Fit, Max iterations and the Referenced / Normalized tab are disabled. |
### Data columns (1-indexed)
| Variable | Default | Column contents |
|------------|---------|---------------------------------------|
| `z_col` | `0` | Sample position *z* (mm) |
| `CA_col` | `1` | Closed-aperture detector signal (V) |
| `FREQ_col` | `3` | Frequency / shot-index channel |
| `OA_col` | `4` | Open-aperture detector signal (V) |
| `REF_col` | `7` | Reference detector signal (V) |
| `FREQ_col` | `9` | Lock-in frequency column (V) |
### Processing flags
| Parameter | Meaning |
|--------------------------------------|-------------------------------------------------------------|
| `use_ref` | Apply the reference-channel correction |
| `use_freq` | Appliy the frequency-channel correction |
| `flip_z` | `1` reverses the sign of the z axis |
| `do_norm_OA`, `do_norm_CA` | Fit and divide out the linear wing baseline |
| `flip_OA`, `flip_CA`, `flip_REF` | Invert a raw channel about its median (`0` or `1`) |
| `flip_OA_disp`, `flip_CA_disp` | Invert the normalized traces about 1 for display/fitting |
| `show_CA` | Plot CA in the right panel; if `False`, plot CA/OA instead |
### Nonlinear coefficients
| Parameter | Meaning | Units | Log units |
|-----------|----------------------------------------|----------|------------|
| `n_2` | 3rd-order nonlinear refractive index | m²/W | cm²/GW |
| `n_3` | 5th-order nonlinear refractive index | m⁴/W² | cm⁴/GW² |
| `n_4` | 7th-order nonlinear refractive index | m⁶/W³ | cm⁶/GW³ |
| `alpha_2` | Two-photon absorption coefficient | m/W | cm/GW |
| `alpha_3` | Three-photon absorption coefficient | m³/W² | cm³/GW² |
| `alpha_4` | Four-photon absorption coefficient | m⁵/W³ | cm⁵/GW³ |
### z-position offsets
`Delta_z_OA`, `Delta_z_CA`, `Delta_z_OACA` (mm) shift the OA, CA, and CA/OA
z-axes independently so that measured and simulated curves line up when the two
detector arms are not perfectly co-registered.
### Sample parameters
| Parameter | Meaning | Units |
|-------------|---------------------------------------------|-------|
| `n` | Linear refractive index | — |
| `L` | Sample thickness | m |
| `T_lin` | Linear transmittance | — |
### Laser parameters
| Parameter | Meaning | Units |
|-------------|---------------------------------------------|-------|
| `E` | Pulse energy | J |
| `lambda` | Wavelength | m |
| `w_0` | Beam waist, HW1/e² of irradiance | m |
| `tau_FWHM` | Pulse duration, FWHM of irradiance | s |
| `M2` | Beam quality parameter M² | — |
### Measurement parameters
| Parameter | Meaning | Units |
|-------------|---------------------------------------------|-------|
| `S` | Linear transmission of the aperture | — |
| `d` | Distance from focus to aperture | m |
### Error estimates
`E_err`, `w_err`, and `tau_err` are fractional uncertainties on the energy,
waist, and pulse duration; they are combined in quadrature into `Tot_err` and
written to the log as the systematic uncertainty on the extracted coefficients.
— `E_err`, `w_err`, `tau_err`, as fractions, propagated into the reported
uncertainty
### Simulation parameters
| Parameter | Default | Meaning |
|-------------|---------|-----------------------------------------------------|
| `z_points` | `76` | Number of z-scan points (must be even) |
| `r_points` | `500` | Radial points at the sample |
| `r_max` | `3` | Radial integration limit, in beam radii *w* |
| `t_points` | `50` | Temporal points |
| `t_max` | `3` | Temporal integration limit, in pulse widths *τ* |
| `ra_points` | `50` | Radial points at the closed aperture |
| `endpts_%` | `10` | Percentage of edge points to use for normalization |
| `z range (sim.)` | `15` | Half-width of the simulated scan, in Rayleigh ranges *z₀*. Simulation mode only |
| `max_iter` | `100` | Maximum iterations for the parameter refinement (Fitting only) |
Memory use scales as `r_points x ra_points x t_points x z_points`, so raising
the grid resolution raises RAM sharply; the interface shows the estimate as you
edit those fields.
## Citing this work
If this program contributes to work you publish, please cite the paper the
method comes from:
> M. R. Ferdinandus, M. Reichert, T. R. Ensley, D. A. Fishman, S. Webster,
> D. J. Hagan, and E. W. Van Stryland, "Measuring small solute nonlinearities in
> solution by dual-arm Z-Scan technique," in *Frontiers in Optics 2012/Laser
> Science XXVIII*, OSA Technical Digest (online) (Optica Publishing Group,
> 2012), paper FM4I.6. <https://doi.org/10.1364/FIO.2012.FM4I.6>
```bibtex
@inproceedings{Ferdinandus2012DualArmZScan,
author = {Ferdinandus, Manuel R. and Reichert, Matthew and
Ensley, Trenton R. and Fishman, Dmitry A. and Webster, Scott and
Hagan, David J. and Van Stryland, Eric W.},
title = {Measuring small solute nonlinearities in solution by dual-arm
{Z}-Scan technique},
booktitle = {Frontiers in Optics 2012/Laser Science XXVIII},
series = {OSA Technical Digest (online)},
publisher = {Optica Publishing Group},
year = {2012},
pages = {FM4I.6},
doi = {10.1364/FIO.2012.FM4I.6},
}
```
The code was written by the paper's first author. It was ported from a MATLAB
implementation of this method, then restructured into a separate simulation
engine and interface; the physics and array shapes follow the original
derivation.
## 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/>.
The full license text is in [LICENSE](LICENSE) — download it from
<https://www.gnu.org/licenses/gpl-3.0.txt> and save it as `LICENSE` in the
repository root. Both source files carry the corresponding notice at the top.
NumPy, SciPy and Matplotlib are all BSD-licensed, so distributing this program
under the GPL alongside them poses no conflict.