Files
ZScan_beam_simulation/ZScan_beam_simulation_1_3_4.py
T
2026-09-11 21:40:48 +00:00

650 lines
30 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ZScan_beam_simulation
======================
Version: 1.3.4 (Python translation of the original MATLAB script)
Date: 06/23/19 (original) - translated to Python
Calculates Open and Closed aperture z-scan curves based on
instantaneous (chi-3) NLR and 2PA. Takes slices in
radius and time, and uses analytic solutions to SVEA dI/dz and dphi/dz
in the thin sample approximation (constant beam size across sample).
Integrates irradiance at end of sample for Open Aperture (OA).
Propagates electric field (square root of irradiance with accumulated
phase) to closed aperture and integrates for Closed Aperture. Done
entirely in vectorized NumPy array form, requiring no Python for-loops
over the physics grid (mirroring the original "no for-loop" MATLAB
matrix approach, though NumPy broadcasting is used instead of
explicit repmat()/permute() calls).
The algorithm is based on the following paper:
1: Reichert, M., et al. (2014). "Temporal, spectral, and polarization
dependence of the nonlinear optical response of carbon disulfide"
Optica 1(6): 436.
Copyright (C) 2017 Manuel 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 <http://www.gnu.org/licenses/>.
-------------------------------------------------------------------------
NOTES ON THE MATLAB -> PYTHON TRANSLATION
-------------------------------------------------------------------------
* MATLAB is 1-indexed and column-major; NumPy is 0-indexed and row-major.
All column indices below have been shifted down by 1 (see the
"columns in data file" section) and every DATA(:,k) reference has
become DATA[:, k-1].
* MATLAB's repmat()/permute() based broadcasting has been replaced with
native NumPy broadcasting, which is equivalent but avoids allocating
the large, fully-expanded intermediate arrays that MATLAB's repmat
would create.
* interp1(...,'spline') -> scipy.interpolate.CubicSpline
interp1(...) [default linear] -> numpy.interp
* besselj(0, x) -> scipy.special.j0
* rmmissing(x) -> x[~numpy.isnan(x)]
* trapz(A, dim) [MATLAB, unit spacing] -> numpy.trapz(A, axis=dim-1)
followed by multiplication by the true spacing (dr, dt, dra), exactly
as done in the original MATLAB code.
* MATLAB's dlmread(path, '', 1, 0) auto-detects the delimiter and skips
the first header row. The Python translation below uses
numpy.genfromtxt() with skip_header=1, which auto-splits on
whitespace. If your data file is comma- or tab-delimited in a way
genfromtxt doesn't auto-detect, pass delimiter=',' or delimiter='\\t'
explicitly.
* MATLAB's .emf output format has no direct NumPy/Matplotlib
equivalent; the export below saves .jpg (and .svg as a vector
substitute for presentation-quality figures) instead of .emf.
"""
import os
import time
import datetime
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import CubicSpline
from scipy.special import j0
# NumPy >= 2.0 renamed trapz() to trapezoid(); keep both names usable.
_trapz = getattr(np, "trapezoid", None) or np.trapz
start_time = time.time()
# =============================================================================
# FILE PARAMETERS
# =============================================================================
# Set write = True to get output.
write = True
import_filepath = (
r""
)
# extra label to append to output files
extra_label = ""
# columns in data file (0-indexed; MATLAB originals were 1-indexed)
z_col = 0 # MATLAB z_col = 1
CA_col = 1 # MATLAB CA_col = 2
OA_col = 4 # MATLAB OA_col = 5
REF_col = 7 # MATLAB REF_col = 8
FREQ_col = 3 # MATLAB FREQ_col = 4
# processing parameters
use_ref = True # use reference channel
flip_z = 1 # flip z-axis
do_norm_OA = True # normalize OA channel
do_norm_CA = True # normalize CA channel
# flip signals
flip_OA = 0
flip_CA = 0
flip_REF = 0
# flip display for fitting
flip_OA_disp = 0
flip_CA_disp = 0
show_CA = True # show CA or OA/CA
# =============================================================================
# INPUT PARAMETERS
# =============================================================================
# Nonlinear parameters
n_2 = 1.02e-18 # 3rd order nonlinear refractive index [m^2/W]
n_3 = 0e-33 # 5th order nonlinear refractive index [m/W]
n_4 = 0e-48 # 7th order nonlinear refractive index [m/W^2]
alpha_2 = 0e-13 # two photon absorption coefficient [m/W]
alpha_3 = 0e-28 # three photon absorption coefficient [m^3/W^2]
alpha_4 = 2.46e-43 # four photon absorption coefficient [m^5/W^3]
# Offset the OA and CA lines if required
Delta_z_OA = 0.05 # OA z-position offset [mm]
Delta_z_CA = 0.23 # CA z-position offset [mm]
Delta_z_OACA = 0.0 # OACA z-position offset [mm]
# Sample parameters
n = 3.0337 # Linear refractive index (Fresnel reflections)
L = 0.188e-3 # Sample thickness [m]
T_lin = 1.0 # Linear transmittance [1]
# Laser parameters
E = 180e-9 # Pulse energy [J]
lambda_ = 2000e-9 # Wavelength [m]
w_0 = 19e-6 # Beam waist HW1/e^2M of I [m]
tau_FWHM = 50e-15 # Pulse duration FWHM of I [s]
M2 = 1.0 # Beam quality parameter
# Measurement parameters
S = 0.33 # Linear transmission of aperture
d = 1.0 # Distance from focus to aperture [m]
# Error parameters
E_err = 10 / 100 # Energy error [%]
w_err = 10 / 100 # Beam waist error [%]
tau_err = 10 / 100 # Pulse duration error [%]
# =============================================================================
# INPUT DATA AND PROCESS REFERENCE TO CLEAN UP DATA
# =============================================================================
# Read the data from the file (auto-detects whitespace delimiter; adjust
# delimiter= if your file uses commas or tabs).
V_DATA = np.genfromtxt(import_filepath, skip_header=1)
# Extract relevant data from voltage data.
Z_DATA = ((-1) ** flip_z) * V_DATA[:, z_col]
FREQ_DATA = V_DATA[:, FREQ_col] # / np.median(V_DATA[:, FREQ_col])
OA_DATA = 2 * np.median(V_DATA[:, OA_col]) * flip_OA + ((-1) ** flip_OA) * V_DATA[:, OA_col]
CA_DATA = 2 * np.median(V_DATA[:, CA_col]) * flip_CA + ((-1) ** flip_CA) * V_DATA[:, CA_col]
# Calculate the scaling factors and scale the reference data if required
if use_ref:
# use the reference channel to clean up the data
REF_DATA = 2 * np.median(V_DATA[:, REF_col]) * flip_REF + ((-1) ** flip_REF) * V_DATA[:, REF_col]
rat = (OA_DATA / np.median(OA_DATA) - 1) / (REF_DATA / np.median(REF_DATA) - 1)
m_rat = np.median(rat)
REF_SCALED = (REF_DATA - np.median(REF_DATA)) * m_rat + np.median(REF_DATA)
REF_SCALED = REF_SCALED / np.median(REF_SCALED)
OA_DATA_CORR = OA_DATA / REF_SCALED
rat = (CA_DATA / np.median(CA_DATA) - 1) / (REF_DATA / np.median(REF_DATA) - 1)
m_rat = np.median(rat)
REF_SCALED = (REF_DATA - np.median(REF_DATA)) * m_rat + np.median(REF_DATA)
REF_SCALED = REF_SCALED / np.median(REF_SCALED)
CA_DATA_CORR = CA_DATA / REF_SCALED
else:
# do not use the reference channel
OA_DATA_CORR = OA_DATA
CA_DATA_CORR = CA_DATA
CAOA_DATA = CA_DATA / (OA_DATA / np.median(OA_DATA))
# =============================================================================
# NORMALIZE THE DATA AND ADJUST FOR SLOPE
# =============================================================================
n_pts = Z_DATA.shape[0]
DATA = np.zeros((n_pts, 11)) # columns 0..10 correspond to MATLAB DATA(:,1..11)
DATA[:, 0] = Z_DATA - np.median(Z_DATA)
DATA[:, 1] = OA_DATA / np.median(OA_DATA)
DATA[:, 2] = OA_DATA_CORR / np.median(OA_DATA_CORR)
DATA[:, 3] = CA_DATA / np.median(CA_DATA)
DATA[:, 4] = CA_DATA_CORR / np.median(CA_DATA_CORR)
endpts = int(np.floor(0.1 * n_pts))
# calculate OA normalization line
if do_norm_OA:
OA_wings = np.vstack([DATA[:endpts, 0:3], DATA[-(endpts + 1):, 0:3]]) # Get data on wings
OA_coeff = np.polyfit(OA_wings[:, 0], OA_wings[:, 2], 1) # Calculate coefficients
norm_OA = np.polyval(OA_coeff, DATA[:, 0]) # Calculate fit line
else:
norm_OA = np.zeros(n_pts) + 1 # flat fit line
# show the original data and fit line
line_width = 1.25
fig1, axes1 = plt.subplots(1, 2, figsize=(12, 5.5), num="Referenced and normalized data")
# show OA data and normalization line
ax = axes1[0]
ax.plot(DATA[:, 0], DATA[:, 1], 'r-')
ax.plot(DATA[:, 0], DATA[:, 2], 'r-', linewidth=line_width)
ax.plot(DATA[:, 0], norm_OA, 'k-', linewidth=line_width)
ax.set_title('Open aperture (raw / referenced)')
ax.set_xlabel('z (mm)')
ax.set_ylabel('Transmission (normalized)')
ax.autoscale(enable=True, tight=True)
ax.set_box_aspect(1 / 1.25)
# calculate CA normalization line
if do_norm_CA:
CA_wings = np.vstack([DATA[:endpts, 0:5], DATA[-(endpts + 1):, 0:5]]) # Get data on wings
CA_coeff = np.polyfit(CA_wings[:, 0], CA_wings[:, 4], 1) # Calculate coefficients
norm_CA = np.polyval(CA_coeff, DATA[:, 0]) # Calculate fit line
else:
norm_CA = np.zeros(n_pts) + 1 # flat fit line
# show the CA data and normalization line
ax = axes1[1]
ax.plot(DATA[:, 0], DATA[:, 3], 'b-')
ax.plot(DATA[:, 0], DATA[:, 4], 'b-', linewidth=line_width)
ax.plot(DATA[:, 0], norm_CA, 'k-', linewidth=line_width)
ax.yaxis.set_label_position('right')
ax.yaxis.tick_right()
ax.set_title('Closed aperture (raw / referenced)')
ax.set_xlabel('z (mm)')
ax.set_ylabel('Transmission (normalized)')
ax.autoscale(enable=True, tight=True)
ax.set_box_aspect(1 / 1.25)
fig1.tight_layout()
# append normalized data to array
DATA[:, 5] = DATA[:, 0] - Delta_z_OA # OA z-axis
DATA[:, 6] = DATA[:, 2] / norm_OA # Normalized OA
DATA[:, 7] = DATA[:, 0] - Delta_z_CA # CA z-axis
DATA[:, 8] = DATA[:, 4] / norm_CA # Normalized CA
DATA[:, 9] = DATA[:, 0] - Delta_z_OACA # OACA z-axis
DATA[:, 10] = DATA[:, 8] / DATA[:, 6] # Normalized OACA
# flip arrays if required
DATA[:, 6] = 2 * flip_OA_disp + ((-1) ** flip_OA_disp) * DATA[:, 6]
DATA[:, 8] = 2 * flip_CA_disp + ((-1) ** flip_CA_disp) * DATA[:, 8]
DATA[:, 10] = 2 * flip_CA_disp + ((-1) ** flip_CA_disp) * DATA[:, 10]
# =============================================================================
# SIMULATION PARAMETERS
# =============================================================================
# Determines the quality of fit, larger the better, but will take longer to
# calculate! Also, you must be careful because it is very easy to make the
# simulation space large enough to run out of RAM. The most important
# parameter here is r_points, which should never be set less than 200, and
# should be more if you have the RAM! This samples the electric field
# distribution after the sample for propagation for the aperture. If
# undersampled it will result in numerical errors, typically a bowing up in
# the middle.
z_points = 75 # Number of z-scan points (must be even)
r_points = 500 # Number of points in radial domain on sample
r_max = 3 # Size of radial integration [w]
t_points = 50 # Number of points in temporal domain
t_max = 3 # Size temporal integration [tau]
ra_points = 50 # Number of points in radial domain at closed aperture
# =============================================================================
# CALCULATED PARAMETERS
# =============================================================================
# physical constants
c = 299792458 # Speed of light [m/s]
epsilon_0 = 8.854187817620e-12 # Permittivity of free space [F/m]
h = 6.62606957e-34 # Planck's constant [J s]
# calculated parameters
tau = tau_FWHM / (2 * np.sqrt(np.log(2))) # Pulse duration HW1/eM of I [s]
k_0 = 2 * np.pi / lambda_ # Wavenumber [m^-1]
alpha = -np.log(T_lin) / L # Linear absorption coefficient [m^-1]
kappa = alpha * lambda_ / (4 * np.pi) # Extinction coefficient [1]
Io = 2 * E / (np.pi ** 1.5 * w_0 ** 2 * tau) # Peak Irradiance [W/m^2]
z_0 = np.pi * w_0 ** 2 / lambda_ # Rayleigh range [m]
w_a = w_0 * (1 + M2 * (d / z_0) ** 2) ** 0.5 # Beam radius at aperture [m]
r_a = w_a * np.sqrt(-0.5 * np.log(1 - S)) # Aperture radius [m]
z_range = (
(np.max(np.abs(DATA[:, 0])) + abs(max(Delta_z_OA, Delta_z_CA, Delta_z_OACA)))
/ (z_0 * 1e3)
) # Full z-scan range [z_0]
Tot_err = np.sqrt(E_err ** 2 + w_err ** 2 + tau_err ** 2) # Total error [1]
# =============================================================================
# INITIALIZATION
# =============================================================================
if alpha_2 + alpha_3 + alpha_4 == 0: # Prevent division by zero
alpha_2 = 1e-20 # This is in here because these
# constants occur in the denominator
if n_2 + n_3 + n_4 == 0: # in certain locations in the
n_2 = 1e-50 # calculation, and thus must not
# be zero or an error would occur
z_lin = np.linspace(-1, 1, z_points + 1) # adjust the space of z-scan position, denser near focus
z = np.sign(z_lin) * (z_lin ** 2)
z = z * z_range * z_0 # Z-scan range [m]
w = w_0 * (1 + M2 * (z / z_0) ** 2) ** 0.5 # Beam radius [m]
with np.errstate(divide='ignore', invalid='ignore'):
R = z + z_0 ** 2 / z # Radius of curvature [m] (inf at focus, as in MATLAB)
zeta = np.arctan(z / z_0) # Gouy shift [rad]
r_vec = np.linspace(0, r_max, r_points + 1)
r = np.outer(w, r_vec) # Radial matrix [m], shape (Nz, Nr)
dr = r[:, 1] # per-z radial spacing, shape (Nz,)
t = np.linspace(0, t_max * tau, t_points + 1) # Temporal vector [s]
dt = t[1]
ra = np.linspace(0, r_a, ra_points + 1) # Aperture radial vector [m]
dra = ra[1]
da = d - z # Distance from sample to aperture [m], shape (Nz,)
# =============================================================================
# CALCULATE IRRADIANCE THROUGH SAMPLE
# =============================================================================
I_r = Io * (w_0 / w)[:, None] ** 2 * np.exp(-2 * (r / w[:, None]) ** 2) # (Nz, Nr) radial irradiance vs z
Delta_n = n_2 * I_r # Index change vs radius and z
Ref = ((n + Delta_n - 1) ** 2 + kappa ** 2) / ((n + Delta_n + 1) ** 2 + kappa ** 2) # Reflectivity
I_r1 = I_r * (1 - Ref) # Irradiance through front surface
I_t = np.exp(-(t / tau) ** 2) # Temporal irradiance distribution
I = I_r1[:, :, None] * I_t[None, None, :] # 3D irradiance (z, r, t) at sample input
if alpha == 0:
denom = alpha_2 + alpha_3 * I + alpha_4 * I ** 2
I_exit = I / (1 + denom * L * I) # 3D irradiance (z, r, t) at sample output
nl_phi = (k_0 * (n_2 + n_3 * I + n_4 * I ** 2) / denom
* np.log(1 + denom * L * I)) # 3D nonlinear phase (z, r, t)
else:
denom = alpha_2 + alpha_3 * I + alpha_4 * I ** 2
I_exit = (alpha * I
/ ((alpha + denom * I) * np.exp(alpha * L) - denom * I)) # 3D irradiance (z, r, t) at sample output
nl_phi = (k_0 * (n_2 + n_3 * I + n_4 * I ** 2) / denom
* (np.log((alpha + denom * I) * np.exp(alpha * L) - denom * I)
- alpha * L - np.log(alpha))) # 3D nonlinear phase (z, r, t)
I = I_exit
G_phase2d = 1j * k_0 * r ** 2 / (2 * R[:, None]) + 1j * zeta[:, None] # (Nz, Nr) Gaussian phase (curvature + Gouy)
G_phase = G_phase2d[:, :, None] # broadcastable over t
E_exit = (np.sqrt(2 / (c * epsilon_0) * I)
* np.exp(1j * nl_phi)
* np.exp(G_phase)) # complex E-field (z, r, t) at sample output
# =============================================================================
# PROPAGATE TO CLOSED APERTURE
# =============================================================================
# Dimensions used below: axis 0 = z, axis 1 = r (on sample), axis 2 = t,
# axis 3 = ra (radius at the aperture). NumPy broadcasting stands in for
# MATLAB's explicit repmat()/permute() calls.
E_EXIT = E_exit[:, :, :, None] # (Nz, Nr, Nt, 1)
R_THING = r[:, :, None, None] # (Nz, Nr, 1, 1)
DA = da[:, None, None, None] # (Nz, 1, 1, 1)
RA = ra[None, None, None, :] # (1, 1, 1, Nra)
with np.errstate(divide='ignore', invalid='ignore'):
A = (k_0 / (1j * DA)) * np.exp(1j * np.pi / (lambda_ * DA) * RA ** 2) # (Nz, 1, 1, Nra)
B = (R_THING
* np.exp(1j * np.pi / (lambda_ * DA) * R_THING ** 2)
* j0(k_0 * R_THING * RA / DA)) # (Nz, Nr, 1, Nra)
DR = dr[:, None, None, None] # (Nz, 1, 1, 1)
integrand = E_EXIT * B # (Nz, Nr, Nt, Nra)
integral_r = _trapz(integrand, axis=1) # (Nz, Nt, Nra) -- trapz over r with unit spacing
integral_r = integral_r[:, None, :, :] # (Nz, 1, Nt, Nra)
E_ap4 = A * integral_r * DR # (Nz, 1, Nt, Nra) complex E-field at closed aperture
E_ap = E_ap4[:, 0, :, :] # (Nz, Nt, Nra)
# =============================================================================
# CALCULATE OA AND CA SIGNALS
# =============================================================================
integral_t_OA = _trapz(I, axis=2) # (Nz, Nr) -- trapz over t with unit spacing
weighted_OA = integral_t_OA * (2 * dt) * r # (Nz, Nr)
integral_r_OA = _trapz(weighted_OA, axis=1) # (Nz,) -- trapz over r with unit spacing
OA = integral_r_OA * (2 * np.pi * dr) # Open Aperture signal
OA = OA / OA[0] # Normalized Open Aperture
integral_t_CA = _trapz(np.abs(E_ap) ** 2, axis=1) # (Nz, Nra) -- trapz over t with unit spacing
weighted_CA = integral_t_CA * (2 * dt) * ra[None, :] # (Nz, Nra)
integral_ra_CA = _trapz(weighted_CA, axis=1) # (Nz,) -- trapz over ra with unit spacing
CA = (c * epsilon_0 / 2) * integral_ra_CA * (2 * np.pi * dra) # Closed Aperture signal
CA = CA / ((CA[0] + CA[-1]) / 2) # Normalized Closed Aperture
CAOA = CA / OA
# =============================================================================
# CALCULATE GOODNESS OF FIT METRICS
# =============================================================================
def rmmissing(arr):
"""Equivalent of MATLAB's rmmissing() for 1D arrays: drop NaNs."""
return arr[~np.isnan(arr)]
z_mm = z * 1e3
OA_spline = CubicSpline(z_mm, OA) # interp1(..., 'spline')
OA_interp = OA_spline(DATA[:, 5])
OA_chi_square_arr = rmmissing(((OA_interp - DATA[:, 1]) ** 2) / OA_interp)
OA_chi_square = np.sum(OA_chi_square_arr)
CA_interp = np.interp(DATA[:, 7], z_mm, CA) # interp1(..., default linear)
CA_chi_square_arr = rmmissing(((CA_interp - DATA[:, 2]) ** 2) / CA_interp)
CA_chi_square = np.sum(CA_chi_square_arr)
CAOA_interp = np.interp(DATA[:, 9], z_mm, CAOA) # interp1(..., default linear)
CAOA_chi_square_arr = rmmissing(((CAOA_interp - DATA[:, 3]) ** 2) / CAOA_interp)
CAOA_chi_square = np.sum(CAOA_chi_square_arr)
# =============================================================================
# PLOT
# =============================================================================
fig2, axes2 = plt.subplots(1, 2, figsize=(12, 5.5), num="Normalized and fit data")
# OA plot
ax = axes2[0]
ax.plot(DATA[:, 5], OA_interp, '-r', linewidth=line_width)
ax.plot(DATA[:, 5], DATA[:, 6], 'r.')
ax.autoscale(enable=True, tight=True)
ax.set_box_aspect(1 / 1.25)
ax.set_title('Open aperture (data / fit)')
ax.set_xlabel('z (mm)')
ax.set_ylabel('T (normalized)')
if show_CA:
# CA plot
ax = axes2[1]
ax.plot(DATA[:, 7], CA_interp, '-b', linewidth=line_width)
ax.plot(DATA[:, 7], DATA[:, 8], 'b.')
ax.yaxis.set_label_position('right')
ax.yaxis.tick_right()
ax.autoscale(enable=True, tight=True)
ax.set_box_aspect(1 / 1.25)
ax.set_title('Closed aperture (data / fit)')
ax.set_xlabel('z (mm)')
ax.set_ylabel('T (normalized)')
else:
# OACA plot
ax = axes2[1]
ax.plot(DATA[:, 9], CAOA_interp, '-b', linewidth=line_width)
ax.plot(DATA[:, 9], DATA[:, 10], 'b.')
ax.yaxis.set_label_position('right')
ax.yaxis.tick_right()
ax.autoscale(enable=True, tight=True)
ax.set_box_aspect(1 / 1.25)
ax.set_title('Closed over open aperture (data / fit)')
ax.set_xlabel('z (mm)')
ax.set_ylabel('T (normalized)')
fig2.tight_layout()
# delta PV comparison
deltaOAdata = 1 - np.min(DATA[:, 6])
deltaOAfit = 1 - np.min(OA_interp)
deltaOAcomp = np.array([deltaOAdata, deltaOAfit])
print("deltaOAcomp =", deltaOAcomp)
deltaCAdata = np.max(DATA[:, 8]) - np.min(DATA[:, 8])
deltaCAfit = np.max(CA_interp) - np.min(CA_interp)
deltaCAcomp = np.array([deltaCAdata, deltaCAfit])
print("deltaCAcomp =", deltaCAcomp)
deltaCAOAdata = np.max(DATA[:, 10]) - np.min(DATA[:, 10])
deltaCAOAfit = np.max(CAOA_interp) - np.min(CAOA_interp)
deltaCAOAcomp = np.array([deltaCAOAdata, deltaCAOAfit])
print("deltaCAOAcomp =", deltaCAOAcomp)
# =============================================================================
# OUTPUT
# =============================================================================
# Set write = True at the top, and define export path as desired.
# Saves both fit and shifted/normalized input data in one file.
if write:
export_filepath = import_filepath.replace('.txt', extra_label + '_fit.txt')
export_data = np.column_stack([
DATA[:, 5], DATA[:, 6], OA_interp,
DATA[:, 7], DATA[:, 8], CA_interp,
DATA[:, 9], DATA[:, 10], CAOA_interp,
])
header = ('Position (mm),OA (Data),OA (Fit),Position (mm),CA (Data),CA (Fit),'
'Position (mm),OACA (Data),OACA (Fit)')
np.savetxt(export_filepath, export_data, delimiter=',', fmt='%.8g',
header=header, comments='', newline='\r\n')
# Write Log
logfile_exportpath = export_filepath.replace('.txt', '_log.txt')
with open(logfile_exportpath, 'w+', newline='\r\n') as logfile_fid:
logfile_fid.write(
f"{datetime.datetime.now()}: Begin Z-scan program: {os.path.abspath(__file__)}.\n\n"
)
logfile_fid.write(f"Import data file {import_filepath}.\n\n")
# Write Data Offsets to Log
logfile_fid.write('Data Offsets:\n')
logfile_fid.write(f' Delta_z_OA: {Delta_z_OA} mm\n')
logfile_fid.write(f' Delta_z_CA: {Delta_z_CA} mm\n\n')
# Write Simulation Parameters to Log
logfile_fid.write('Simulation Parameters:\n')
logfile_fid.write(f' z_points: {z_points}\n')
logfile_fid.write(f' z_range: {2 * z_range:6.3f} z_0\n')
logfile_fid.write(f' r_points: {r_points}\n')
logfile_fid.write(f' r_max: {r_max} w\n')
logfile_fid.write(f' t_points: {t_points}\n')
logfile_fid.write(f' t_max: {r_max} tau\n')
logfile_fid.write(f' ra_points: {ra_points}\n\n')
logfile_fid.write('Processing Parameters:\n')
logfile_fid.write(f' use_ref: {int(use_ref)}\n')
logfile_fid.write(f' flip_z: {flip_z}\n')
logfile_fid.write(f' do_norm_OA: {int(do_norm_OA)}\n')
logfile_fid.write(f' do_norm_CA: {int(do_norm_CA)}\n')
logfile_fid.write(f' flip_OA: {flip_OA}\n')
logfile_fid.write(f' flip_CA: {flip_CA}\n')
logfile_fid.write(f' flip_REF: {flip_REF}\n')
logfile_fid.write(f' flip_OA_disp: {flip_OA_disp}\n')
logfile_fid.write(f' flip_CA_disp: {flip_CA_disp}\n\n')
# Write Fit Parameters to Log
logfile_fid.write('Fit Parameters:\n')
logfile_fid.write(f' n_2: {n_2 * 1e13} cm^2/GW\n')
logfile_fid.write(f' n_3: {n_3 * 1e26} cm^4/GW^2\n')
logfile_fid.write(f' n_4: {n_4 * 1e39} cm^6/GW^3\n\n')
logfile_fid.write(f' alpha_2: {alpha_2 * 1e11} cm/GW\n')
logfile_fid.write(f' alpha_3: {alpha_3 * 1e24} cm^3/GW^2\n')
logfile_fid.write(f' alpha_4: {alpha_4 * 1e37} cm^5/GW^3\n\n')
logfile_fid.write(f' E: {E * 1e9} nJ\n')
logfile_fid.write(f' I_0: {Io * 1e-13:6.3f} GW/cm^2\n')
logfile_fid.write(f' lambda: {lambda_ * 1e9} nm\n')
logfile_fid.write(f' w_0 (HW1/e^2M): {w_0 * 1e6} um\n')
logfile_fid.write(f' z_0: {z_0 * 1e3:6.3f} mm\n')
logfile_fid.write(f' tau (FWHM): {tau_FWHM * 1e15} fs\n')
logfile_fid.write(f' tau (HW1/eM): {tau * 1e15:6.3f} fs\n')
logfile_fid.write(f' M^2: {M2}\n\n')
logfile_fid.write(f' n: {n}\n')
logfile_fid.write(f' L: {L * 1e3} mm\n')
logfile_fid.write(f' T_lin: {T_lin}\n')
logfile_fid.write(f' kappa: {kappa:6.3f}\n\n')
logfile_fid.write(f' S: {S}\n')
logfile_fid.write(f' d: {d * 1e3} mm\n\n')
# deltaPV comparisons
logfile_fid.write('DeltaT_PV comparison:\n')
logfile_fid.write(f' Delta_OA_comp: {np.round(deltaOAcomp, 3)} (data / fit)\n')
logfile_fid.write(f' Delta_CA_comp: {np.round(deltaCAcomp, 3)} (data / fit)\n')
logfile_fid.write(f' Delta_CAOA_comp: {np.round(deltaCAOAcomp, 3)} (data / fit)\n\n')
# write fit quality parameters to log
logfile_fid.write('Fit Quality:\n')
logfile_fid.write(f' OA_chi^2: {OA_chi_square:6.3f}\n')
logfile_fid.write(f' CA_chi_2: {CA_chi_square:6.3f}\n')
logfile_fid.write(f' CAOA_chi_2: {CAOA_chi_square:6.3f}\n\n')
# write error estimates to log
logfile_fid.write('Error estimates:\n')
logfile_fid.write(f' E_err: {E_err * 100} %\n')
logfile_fid.write(f' w_err: {w_err * 100} %\n')
logfile_fid.write(f' tau_err: {tau_err * 100} %\n')
logfile_fid.write(f' Tot_err: {Tot_err * 100:6.2f} %\n\n')
# save a picture of the plot
split_ind = export_filepath.find('.txt')
picture_filename = export_filepath[:split_ind] + '.jpg'
fig2.savefig(picture_filename, format='jpg', dpi=200)
# NOTE: MATLAB's saveas(..., 'emf') has no direct Matplotlib
# equivalent. An .svg vector file is saved instead as a
# presentation-quality substitute (edit in Inkscape/Illustrator,
# or convert to .emf externally if required).
picture_filename_vector = export_filepath[:split_ind] + '.svg'
fig2.savefig(picture_filename_vector, format='svg')
# write elapsed time to log
el_time = time.time() - start_time
logfile_fid.write(f'Export results to {export_filepath}.\n')
logfile_fid.write(f'Elapsed time is {el_time:6.2f} seconds.\n\n')
plt.show()