From 5ec896eb38a2f50a6d9c82cafbf682a99dfa6857 Mon Sep 17 00:00:00 2001 From: manuel Date: Sat, 12 Sep 2026 20:53:13 +0000 Subject: [PATCH] Upload files to "/" --- README.md | 268 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 268 insertions(+) diff --git a/README.md b/README.md index 45d58df..c8c8ecd 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,270 @@ # ZScan_beam_simulation +Simulation and fitting of open-aperture (OA) and closed-aperture (CA) Z-scan +curves for instantaneous nonlinear refraction and multiphoton absorption. + +Version **1.3.4** — Python translation of the original MATLAB script (original +dated 06/23/19). + +The script slices the beam in radius and time, applies the analytic +thin-sample solutions to the SVEA equations for `dI/dz` and `dphi/dz`, +integrates the irradiance at the exit face for the OA signal, then propagates +the complex field (amplitude with accumulated nonlinear phase) via a +Hankel/Fresnel integral to the closed aperture and integrates there for the CA +signal. Everything runs as vectorized NumPy broadcasting — there are no Python +loops over the physics grid. + +Licensed under the **GNU General Public License v3.0 or later**. See +[License](#license). + +--- + +## Reference + +The method implemented here is described in: + +> 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. +> + +Abstract page: + +If you use this program in work that you publish, please cite that paper. + +--- + +## Contents + +- [Requirements](#requirements) +- [Quick start](#quick-start) +- [Input data format](#input-data-format) +- [Parameters](#parameters) +- [Outputs](#outputs) +- [Numerical accuracy and memory](#numerical-accuracy-and-memory) +- [MATLAB → Python translation notes](#matlab--python-translation-notes) +- [License](#license) + +--- + +## Requirements + +- Python 3.8+ +- NumPy (1.x or 2.x — the script handles the `trapz` → `trapezoid` rename) +- SciPy (`scipy.interpolate.CubicSpline`, `scipy.special.j0`) +- Matplotlib + +```bash +pip install numpy scipy matplotlib +``` + +## Quick start + +1. Clone the repository and open `ZScan_beam_simulation_1_3_4.py` in an editor. +2. Set `import_filepath` to your measured Z-scan data file. +3. Set the column indices (`z_col`, `CA_col`, `OA_col`, `REF_col`, `FREQ_col`) + to match that file. **These are 0-indexed**, unlike the MATLAB original. +4. Enter the sample, laser, and measurement parameters, and your starting + guesses for the nonlinear coefficients. +5. Run it: + +```bash +python ZScan_beam_simulation_1_3_4.py +``` + +All configuration lives in the `FILE PARAMETERS` and `INPUT PARAMETERS` blocks +at the top of the file — there is no command-line interface. The script is +intended to be edited, run, inspected, and re-run while you tune the fit by +hand. + +Two figure windows open: + +- **Referenced and normalized data** — raw and reference-corrected OA/CA traces + with the linear wing-normalization lines overlaid. Use this to confirm the + reference channel and the baseline are behaving before you trust the fit. +- **Normalized and fit data** — normalized data points against the simulated + curves. + +Set `write = True` to export results (see [Outputs](#outputs)). + +## Input data format + +A whitespace-delimited text file with **one header row**, read with +`numpy.genfromtxt(path, skip_header=1)`. Each column is addressed by index: + +| 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) | + +If your file is comma- or tab-delimited in a way `genfromtxt` does not +auto-detect, pass `delimiter=','` or `delimiter='\t'` in the `genfromtxt` call. + +### Reference correction and normalization + +When `use_ref = True`, the reference channel is rescaled to the OA (and +separately to the CA) channel through the median of their fractional +fluctuations, then divided out. This removes correlated shot-to-shot energy +noise without over- or under-subtracting. + +Each channel is then divided by its median, and a straight line fitted to the +outer 10 % of points on each wing is divided out to remove residual linear +drift (`do_norm_OA`, `do_norm_CA`). Set either to `False` to use a flat +baseline of 1 instead. + +## Parameters + +### Processing flags + +| Parameter | Meaning | +|--------------------------------------|-------------------------------------------------------------| +| `use_ref` | Apply the reference-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 (the fit parameters) + +| 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³ | + +These coefficients appear in denominators in the analytic solutions, so if all +the `n` terms or all the `alpha` terms are zero the script substitutes a +negligible value (`1e-50`, `1e-20`) rather than dividing by zero. The result is +numerically indistinguishable from an unset term. + +### Alignment 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, laser, and measurement + +| Parameter | Meaning | Units | +|-------------|---------------------------------------------|-------| +| `n` | Linear refractive index (Fresnel reflections)| — | +| `L` | Sample thickness | m | +| `T_lin` | Linear transmittance | — | +| `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² | — | +| `S` | Linear transmission of the aperture | — | +| `d` | Distance from focus to aperture | m | + +`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. + +### Simulation grid + +| Parameter | Default | Meaning | +|-------------|---------|-----------------------------------------------------| +| `z_points` | `75` | 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 | + +The z grid is quadratically spaced (`z = sign(z_lin)·z_lin²`), so points bunch +near focus where the signal changes fastest. The scan range is derived +automatically from the data extent plus the largest `Delta_z` offset. + +## Outputs + +With `write = True`, the export path is the input path with `.txt` replaced by +`_fit.txt`. Four files are produced: + +| File | Contents | +|---------------------|-------------------------------------------------------------------| +| `*_fit.txt` | CSV, 9 columns: z / data / fit for each of OA, CA, and CA/OA | +| `*_fit_log.txt` | Full run log — every parameter, ΔTPV comparisons, χ², errors, elapsed time | +| `*_fit.jpg` | Raster copy of the fit figure at 200 dpi | +| `*_fit.svg` | Vector copy of the same figure | + +The log is the provenance record for a fit: it captures the input file, all +processing flags, the nonlinear coefficients in practical units, derived +quantities (`I_0`, `z_0`, `tau` HW1/eM, `kappa`), the peak-valley comparison +between data and fit, the χ² values, and the total systematic error. + +Note that `extra_label` and the `_fit` suffix are inserted by a literal +`.txt` replacement, so the input file should end in `.txt`. + +## Numerical accuracy and memory + +`r_points` is the parameter that matters most. It sets how finely the exit +field is sampled before the Hankel propagation to the aperture. **Do not go +below 200** — undersampling shows up as a spurious upward bow in the middle of +the CA curve, which is easy to mistake for real physics. + +The propagation builds a 4-D complex array over +(z, rsample, t, raperture), so memory grows as the product +of all four grids: + +``` +bytes ≈ 16 × (z_points+1) × (r_points+1) × (t_points+1) × (ra_points+1) +``` + +At the defaults that is roughly 1.6 GB for the integrand alone. Doubling +`r_points` doubles it. Raise the grids deliberately, and watch RAM before +launching a long run. + +## MATLAB → Python translation notes + +- MATLAB is 1-indexed and column-major; NumPy is 0-indexed and row-major. All + column indices were shifted down by one, and `DATA(:,k)` became `DATA[:, k-1]`. +- `repmat()`/`permute()` broadcasting was replaced with native NumPy + broadcasting — equivalent results, without allocating the fully expanded + intermediates MATLAB would materialize. +- `interp1(...,'spline')` → `scipy.interpolate.CubicSpline`; default (linear) + `interp1` → `numpy.interp`. +- `besselj(0, x)` → `scipy.special.j0`. +- `rmmissing(x)` → `x[~numpy.isnan(x)]`. +- `trapz(A, dim)` (unit spacing) → `numpy.trapz(A, axis=dim-1)` followed by + multiplication by the true spacing (`dr`, `dt`, `dra`), exactly as the + original MATLAB did. +- `dlmread(path, '', 1, 0)` → `numpy.genfromtxt(path, skip_header=1)`. +- MATLAB's `.emf` export has no Matplotlib equivalent; `.svg` is written + instead as the presentation-quality vector format. Convert externally if you + need `.emf`. + +## License + +Copyright © 2017 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 belongs in a `COPYING` (or `LICENSE`) file at the root of +the repository; the canonical text is at +. The same notice is reproduced in the +header of `ZScan_beam_simulation_1_3_4.py`, and should be kept in any file added +to the project. SPDX identifier: `GPL-3.0-or-later`. + +Note that the GPL covers the program only. It places no conditions on data you +measure, the fit results the program produces, or anything you write about them.