diff --git a/README.md b/README.md index e0f8d32..f4beb84 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,229 @@ -# ZScan_beam_simulation_GUI +# 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 + +- **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. **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. +2. **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. +3. **Enter the measurement parameters** — pulse energy, wavelength, beam waist, + pulse width, sample thickness and refractive index, aperture transmittance. +4. **Run Simulation** to overlay the simulated curves on the data. +5. **Refine Fit** — tick the coefficients to vary and let the optimizer adjust + them. It runs in the background with a live iteration count. +6. **Export** to write the fit data, log and images next to the input file. + +### Exported files + +Written alongside the input file, with an optional extra label in the name: + +| File | Contents | +|---|---| +| `_fit.` | CSV of position, data and fit for the OA, CA and CA/OA curves | +| `_fit_log.txt` | Every parameter, fit-quality metric and output path | +| `_fit.jpg` / `.svg` | Fit figure, raster and vector | +| `_fit_ref.jpg` / `.svg` | Referenced/normalized figure | + +## 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 + +
+Full parameter list + +**Data columns** — `z_col`, `CA_col`, `OA_col`, `REF_col`, `FREQ_col` (1-indexed) + +**Processing flags** — `use_ref`, `use_freq`, `flip_z`, `do_norm_OA`, +`do_norm_CA`, and per-channel sign flips for the raw and displayed traces + +**Nonlinear coefficients** — `n_2` (m²/W), `n_3` (m⁴/W²), `n_4` (m⁶/W³), +`alpha_2` (m/W), `alpha_3` (m³/W²), `alpha_4` (m⁵/W³) + +**z-position offsets** — `Delta_z_OA`, `Delta_z_CA`, `Delta_z_OACA` (mm), to +align each measured curve with the simulated focus + +**Sample** — `n` (linear index), `L` (thickness), `T_lin` (linear transmittance) + +**Laser** — `E` (pulse energy), `lambda_`, `w_0` (waist), `tau_FWHM`, `M2` + +**Measurement** — `S` (aperture transmittance), `d` (focus-to-aperture distance) + +**Error estimates** — `E_err`, `w_err`, `tau_err`, as fractions, propagated into +the reported uncertainty + +**Simulation grid** — `z_points`, `r_points`, `r_max`, `t_points`, `t_max`, +`ra_points`, `endpts_percent`, `max_iterations` + +
+ +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. + +```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 . + +The full license text is in [LICENSE](LICENSE) — download it from + 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.