# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""NumPy reference implementation of the propagation model, for validation.
solprop integrates this package's envelope UPPE (:mod:`pnps.bridge`). Everything
here is the *same* model written as whole-array NumPy, small enough to read in one
sitting and slow enough to be used only on test grids:
- :func:`apply_linear` -- the exact linear propagator ``exp(L z)``;
- :func:`nonlinear_rhs` -- the Kerr term of the UPPE in the spectral domain;
- :func:`first_born_signal` -- the first-order (undepleted-pump) four-wave-mixing
signal by Gauss-Legendre quadrature of the linearly propagated source;
- :func:`linear_diagnostics`, :func:`operator_admittance` and
:func:`time_edge_fraction` -- the per-save diagnostics and the measure, against
which the fused host reduction is checked.
The operator is described by an :class:`OperatorTables` record, which can be built two
ways, deliberately:
- :func:`materials_tables` from this package's own materials and grids -- the
*independent* operator, sharing no code with solprop, so agreement with solprop's
propagation validates solprop's integration of it;
- :func:`pnps.bridge.bridge_tables` from the solprop objects the bridge configured --
the *configured* operator, which isolates the integrator from the operator assembly
when a discrepancy has to be located.
The state is ``E[ky, kx, omega]``, the unnormalised 3-D DFT of the field in V/m, in
the FFT sign convention (every physical phase carries a minus sign). The linear
operator is
``L = -i (Re k_z - frame(omega)) - |Im k_z| - gamma_omega(omega)``
with ``k_z = sqrt(k(omega)^2 - kperp^2)`` on the principal branch and ``frame`` the
co-moving subtraction ``beta1 omega + beta0_ref``; the transverse-wavevector ramp
``gamma_k(kx, ky)``, when the configuration has one, damps as ``gamma_omega`` does.
"""
from dataclasses import dataclass
from typing import Any
import numpy as np
from jaxtyping import Bool, Complex, Float
from scipy.constants import c, epsilon_0
from solprop.boundaries import Absorber
from solprop.grid import EnvelopeGrid, FreeGrid
from solprop.linear import Frame
from solprop.spatial import SpatialDispersion, SpatialMedium
from solprop.spatial_absorber import SpatialAbsorberDesign
from pnps.absorber import transverse_rate, transverse_strength
from pnps.flux import axial_admittance
from pnps.grids import SpaceGrid
from pnps.materials import beta0_ref, beta1_ref, silica_k2, silica_raman_shape
from pnps.setup import Setup
__all__ = [
"KERR_PREFACTOR",
"MU",
"OperatorTables",
"admittance_weight",
"apply_linear",
"configured_tables",
"first_born_signal",
"linear_diagnostics",
"materials_tables",
"nonlinear_rhs",
"operator_admittance",
"time_edge_fraction",
]
KERR_PREFACTOR = 0.75 * epsilon_0 # (3/4) eps_0, envelope Kerr without THG
#: The permeability in the UPPE prefactor ``-i mu omega^2 / (2 Re k_z)``, H/m, written
#: as ``1 / (eps_0 c^2)``, the form solprop's prefactor takes, so that both operators
#: carry the same rounded constant.
MU = 1.0 / (epsilon_0 * c**2)
[docs]
@dataclass(frozen=True)
class OperatorTables:
"""Separable tables of the propagation operator (never materialised in 3-D).
Attributes
----------
omega : numpy.ndarray
Absolute angular frequency, FFT-ordered, ``(nt,)``, rad/s.
k2 : numpy.ndarray
Material wavenumber squared ``(n(omega) omega / c)^2``, complex, ``(nt,)``,
rad^2/m^2, zero off the active band. Real for a lossless index.
kperp2 : numpy.ndarray
``kx^2 + ky^2`` indexed ``[iy, ix]``, ``(n, n)``, rad^2/m^2.
frame : numpy.ndarray
Co-moving phase rate subtracted from ``Re k_z``, ``(nt,)``, rad/m.
gamma_omega : numpy.ndarray
Spectral absorber, an *amplitude* rate, ``(nt,)``, 1/m.
gamma_lap : numpy.ndarray
The lap budget's share of ``gamma_omega``, ``(nt,)``, 1/m; the rest is the
band edges'.
gd_band : numpy.ndarray
Indicator (0/1) of the bins the group-delay lap budget absorbs, ``(nt,)``.
chi3 : float
Third-order susceptibility multiplying ``(3/4) eps_0 |E|^2 E``, m^2/V^2.
active : numpy.ndarray or None
solprop's hard band limit: the field is held at zero outside this boolean
``(nt,)`` mask. ``None`` for this package's own operator, which damps those
bins instead of zeroing them.
evanescent_clamp : float or None
Ceiling on the evanescent field attenuation ``|Im k_z|``, 1/m; ``None`` for
the unclamped physical decay.
raman_fraction : float
The share f_R of chi3 carried by the delayed Raman response, 0 for none.
raman_shape : numpy.ndarray or None
The unit-integral Raman shape ``h_R`` sampled at lags ``k delta_t``,
``k = 0 .. n_t - 1``, in 1/s; None without Raman.
gamma_k : numpy.ndarray or None
The transverse-wavevector ramp's amplitude rate, ``(n_y, n_x)``, 1/m; None
for none.
"""
omega: Float[np.ndarray, " n_omega"]
k2: Complex[np.ndarray, " n_omega"]
kperp2: Float[np.ndarray, "n_y n_x"]
frame: Float[np.ndarray, " n_omega"]
gamma_omega: Float[np.ndarray, " n_omega"]
gamma_lap: Float[np.ndarray, " n_omega"]
gd_band: Float[np.ndarray, " n_omega"]
chi3: float
active: Bool[np.ndarray, " n_omega"] | None
evanescent_clamp: float | None
raman_fraction: float = 0.0
raman_shape: Float[np.ndarray, " n_t"] | None = None
gamma_k: Float[np.ndarray, "n_y n_x"] | None = None
[docs]
def materials_tables(setup: Setup) -> OperatorTables:
"""Build the operator from this package's own materials and grids.
The independent operator: the index through :func:`pnps.materials.silica_index`
(optmat's fit evaluated here rather than by solprop), this package's momentum
axis, the co-moving frame ``beta1_ref omega + beta0_ref``,
unclamped evanescent decay and no hard band limit -- no code shared with
solprop's operator assembly. The nonlinearity is the instantaneous Kerr term
with the total chi3: these tables carry no Raman response.
Parameters
----------
setup : Setup
The configuration.
Returns
-------
OperatorTables
The independent operator tables.
"""
tgrid, sgrid = setup.tgrid, setup.sgrid
omega = tgrid.omega
k2 = silica_k2(tgrid, absorption=setup.cfg.absorption)
return OperatorTables(
omega=omega,
k2=k2,
kperp2=_kperp2(sgrid),
frame=beta1_ref(tgrid.lam0) * omega + beta0_ref(tgrid.lam0),
gamma_omega=setup.gamma_omega,
gamma_lap=setup.gamma_lap,
gd_band=setup.gd_band,
chi3=setup.chi3,
active=None,
evanescent_clamp=None,
gamma_k=_independent_gamma_k(setup),
**_raman_tables(setup),
)
def _kperp2(sgrid: SpaceGrid) -> Float[np.ndarray, "n_y n_x"]:
"""Return ``kx^2 + ky^2`` indexed ``[iy, ix]``.
Parameters
----------
sgrid : SpaceGrid
The transverse grid; its momentum axis ``kx`` is shared by x and y.
Returns
-------
numpy.ndarray
The squared transverse wavenumber, ``(n_y, n_x)``, rad^2/m^2.
"""
return sgrid.kx[:, None] ** 2 + sgrid.kx[None, :] ** 2
def _kz_parts(
tables: OperatorTables,
) -> tuple[
Float[np.ndarray, "n_y n_x n_omega"],
Float[np.ndarray, "n_y n_x n_omega"],
Bool[np.ndarray, "n_y n_x n_omega"],
]:
"""Return ``Re k_z``, the decay rate ``|Im k_z|`` (clamped) and the evanescent set.
All three are ``(n, n, nt)``. The decay is the principal root's imaginary part:
the physical evanescent decay where ``Re(k^2) < kperp^2``, and the material
absorption of a complex index elsewhere; only the evanescent part is subject to
the clamp.
Parameters
----------
tables : OperatorTables
The operator.
Returns
-------
kz_re : numpy.ndarray
``Re k_z``, ``(n_y, n_x, n_omega)``, rad/m.
kz_im : numpy.ndarray
The decay rate ``|Im k_z|``, clamped on the evanescent set when the operator
has a clamp, ``(n_y, n_x, n_omega)``, 1/m.
evanescent : numpy.ndarray
Boolean mask of the bins with ``Re(k^2 - kperp^2) <= 0``,
``(n_y, n_x, n_omega)``.
"""
bsq = tables.k2[None, None, :] - tables.kperp2[:, :, None]
kz = np.sqrt(bsq.astype(complex))
kz_re, kz_im = np.real(kz), np.abs(np.imag(kz))
evanescent = np.real(bsq) <= 0.0
if tables.evanescent_clamp is not None:
kz_im = np.where(evanescent, np.minimum(kz_im, tables.evanescent_clamp), kz_im)
return kz_re, kz_im, evanescent
def _band_limit(
e: Complex[np.ndarray, "n_y n_x n_omega"], tables: OperatorTables
) -> Complex[np.ndarray, "n_y n_x n_omega"]:
"""Zero the bins outside the hard band limit, when the operator has one.
Parameters
----------
e : numpy.ndarray
Spectral state ``(n_y, n_x, n_omega)``, V/m (unnormalised DFT).
tables : OperatorTables
The operator; ``tables.active`` is the band limit, or ``None`` for none.
Returns
-------
numpy.ndarray
``e`` itself when there is no band limit, otherwise a band-limited copy.
"""
if tables.active is None:
return e
return np.where(tables.active[None, None, :], e, 0.0)
[docs]
def apply_linear(
e: Complex[np.ndarray, "n_y n_x n_omega"], tables: OperatorTables, dz: float
) -> Complex[np.ndarray, "n_y n_x n_omega"]:
"""Apply the exact linear propagator ``exp(L dz)`` elementwise.
Parameters
----------
e : numpy.ndarray
Spectral state ``(n, n, nt)``.
tables : OperatorTables
The operator.
dz : float
Propagation distance in m.
Returns
-------
numpy.ndarray
``exp(L dz) e``, band-limited when the operator has a hard band limit.
"""
kz_re, kz_im, _ = _kz_parts(tables)
phase = kz_re - tables.frame[None, None, :]
damp = kz_im + tables.gamma_omega[None, None, :]
if tables.gamma_k is not None:
damp = damp + tables.gamma_k[:, :, None]
return _band_limit(e * np.exp(dz * (-1j * phase - damp)), tables)
def _independent_gamma_k(setup: Setup) -> Float[np.ndarray, "n_y n_x"] | None:
"""Return this package's own transverse ramp as an amplitude rate, or None.
Parameters
----------
setup : Setup
The configuration.
Returns
-------
numpy.ndarray or None
Half the ramp's power rate, ``(n_y, n_x)``, 1/m; None without the ramp.
"""
cfg = setup.cfg
if not cfg.transverse_absorber:
return None
strength = transverse_strength(setup.tgrid, setup.sgrid, cfg.transverse_fraction)
return transverse_rate(setup.sgrid.kx, strength, cfg.transverse_fraction) / 2
def _raman_tables(setup: Setup) -> dict[str, Any]:
"""Return the Raman fields of an operator record for a configuration.
Parameters
----------
setup : Setup
The configuration; its ``raman_fraction`` is 0 without Raman.
Returns
-------
dict
``raman_fraction`` and ``raman_shape`` (None without Raman).
"""
if setup.raman_fraction == 0.0:
return {"raman_fraction": 0.0, "raman_shape": None}
lags = np.arange(setup.tgrid.nt) * setup.tgrid.delta_t
return {
"raman_fraction": setup.raman_fraction,
"raman_shape": silica_raman_shape(lags),
}
def _delayed_intensity(
intensity: Float[np.ndarray, "n_y n_x n_t"],
shape: Float[np.ndarray, " n_t"],
delta_t: float,
) -> Float[np.ndarray, "n_y n_x n_t"]:
"""Convolve the intensity causally with the Raman shape along time.
``(h * I)(t) = int_0^T h(s) I(t - s) ds`` by the rectangle rule (the trapezoid
rule, since ``h(0) = 0``), as a *linear* convolution over the window: both are
zero-padded to twice the window, so the response's tail does not wrap onto the
pulse. Time index 0 is ``t = -T/2``, so the window's index order is chronological.
Parameters
----------
intensity : numpy.ndarray
``|A|^2`` on the window, time last.
shape : numpy.ndarray
The Raman shape at lags ``k delta_t``, 1/s.
delta_t : float
The sample spacing, s.
Returns
-------
numpy.ndarray
The delayed intensity, in the units of ``intensity``.
"""
n_t = intensity.shape[-1]
product = np.fft.rfft(intensity, 2 * n_t, axis=-1) * np.fft.rfft(shape, 2 * n_t)
return np.fft.irfft(product, 2 * n_t, axis=-1)[..., :n_t] * delta_t
[docs]
def nonlinear_rhs(
e: Complex[np.ndarray, "n_y n_x n_omega"], tables: OperatorTables
) -> Complex[np.ndarray, "n_y n_x n_omega"]:
"""Evaluate the nonlinear term of the UPPE in the spectral domain.
Transforms to (y, x, t), evaluates the envelope polarisation
``(3/4) eps_0 chi3 [(1 - f_R) |A|^2 + f_R (h_R * |A|^2)] A`` (the instantaneous
Kerr term alone without Raman), transforms back, and applies the UPPE prefactor
``-i omega mu / (2 Re k_z / omega)``. Where ``Re k_z^2 <= 0`` (or omega <= 0)
the prefactor is guarded to ``-i omega / 2`` -- those bins carry no propagating
field.
Parameters
----------
e : numpy.ndarray
Spectral state ``(n, n, nt)``.
tables : OperatorTables
The operator.
Returns
-------
numpy.ndarray
``dE/dz`` from the nonlinearity, band-limited when the operator has a hard
band limit.
"""
et = np.fft.ifftn(e, axes=(-3, -2, -1))
intensity = np.abs(et) ** 2
if tables.raman_shape is not None:
delta_t = 2 * np.pi / (len(tables.omega) * (tables.omega[1] - tables.omega[0]))
f_r = tables.raman_fraction
intensity = (1 - f_r) * intensity + f_r * _delayed_intensity(
intensity, tables.raman_shape, delta_t
)
pt = (KERR_PREFACTOR * tables.chi3) * intensity * et
pw = np.fft.fftn(pt, axes=(-3, -2, -1))
omega = tables.omega[None, None, :]
bsq = np.real(tables.k2)[None, None, :] - tables.kperp2[:, :, None]
propagating = (bsq > 0) & (omega > 0)
# The division is written through the intermediate n_nl = Re k_z / (mu omega).
nnl = np.where(
propagating,
np.sqrt(np.maximum(bsq, 0.0)) / (MU * np.where(omega > 0, omega, 1.0)),
1.0,
)
return _band_limit((-1j * omega / (2 * nnl)) * pw, tables)
[docs]
def first_born_signal(
e_in: Complex[np.ndarray, "n_y n_x n_omega"],
tables: OperatorTables,
z_end: float,
n_nodes: int = 32,
region: Bool[np.ndarray, "n_y n_x n_omega"] | None = None,
) -> Float[np.ndarray, " n_omega"]:
"""First-Born (undepleted-pump) signal-region spectrum at ``z_end``.
The pumps evolve with the exact linear propagator, ``E_p(z) = exp(L z) E_in``;
the first-order signal is
``E_1(Z) = integral_0^Z exp(L (Z - z)) P[E_p(z)] dz``
with ``P`` the full nonlinear term of the UPPE projected onto the signal region
(the TG quadrant ``kx < 0, ky < 0`` unless another is given). Projecting the
*full* Kerr polarisation picks up every
frequency/momentum combination that lands in the region, with all coefficient
bookkeeping included for free. The integral is evaluated by Gauss-Legendre
quadrature; each node costs one nonlinear-term evaluation (one FFT pair).
Parameters
----------
e_in : numpy.ndarray
Input state ``(n, n, nt)`` at z = 0.
tables : OperatorTables
The operator.
z_end : float
Slab position to evaluate at, in m.
n_nodes : int
Gauss-Legendre nodes over ``[0, z_end]``.
region : numpy.ndarray or None, optional
The signal region as a mask of the state (:func:`pnps.geometry.region_mask`);
None for the TG quadrant.
Returns
-------
numpy.ndarray
The Born prediction of ``i_omega_full`` (region-summed spectrum), shape
``(nt,)`` -- directly comparable with a full simulation's ``i_omega_full``
at the same position and low pulse energy, once its linear part has been
subtracted at field level.
"""
n = e_in.shape[0]
if region is None:
inside = np.zeros(e_in.shape, dtype=bool)
inside[n // 2 :, n // 2 :, :] = True
else:
inside = region
nodes, weights = np.polynomial.legendre.leggauss(n_nodes)
z_nodes = 0.5 * z_end * (nodes + 1.0)
z_weights = 0.5 * z_end * weights
born = np.zeros_like(e_in)
for z, w in zip(z_nodes, z_weights, strict=True):
pump = apply_linear(e_in, tables, float(z))
source = nonlinear_rhs(pump, tables)
# Project onto the signal region and back-propagate to z_end.
source[~inside] = 0.0
born += w * apply_linear(source, tables, float(z_end - z))
return np.sum(np.where(inside, np.abs(born) ** 2, 0.0), axis=(0, 1))
[docs]
def linear_diagnostics(
e: Complex[np.ndarray, "n_y n_x n_omega"],
tables: OperatorTables,
) -> dict[str, float]:
"""Return the per-save energy and absorption diagnostics.
The reference for the fused host reduction (:mod:`pnps.reduce_numba`).
Parameters
----------
e : numpy.ndarray
Spectral state ``(n, n, nt)``.
tables : OperatorTables
The operator.
Returns
-------
dict of float
``absorb_omega``, ``absorb_lap`` and ``absorb_k``: the instantaneous measured
absorption rates of the band edges' absorber, of the lap budget and of the
transverse-wavevector ramp; ``gd_band_power``: the fraction of the energy in the
bins the lap budget absorbs. ``|E|^2`` is weighted by the admittance ``eta``
(zero off the operator's band).
"""
p = admittance_weight(tables) * np.abs(e) ** 2
return {
"absorb_omega": float(
np.sum((tables.gamma_omega - tables.gamma_lap)[None, None, :] * p)
),
"absorb_lap": float(np.sum(tables.gamma_lap[None, None, :] * p)),
"absorb_k": (
0.0
if tables.gamma_k is None
else float(np.sum(tables.gamma_k[:, :, None] * p))
),
"gd_band_power": float(np.sum(tables.gd_band[None, None, :] * p) / np.sum(p)),
}
[docs]
def admittance_weight(tables: OperatorTables) -> Float[np.ndarray, "n_y n_x n_omega"]:
"""Return the weight of ``|E|^2`` in every measured energy, ``(n, n, nt)``.
Parameters
----------
tables : OperatorTables
The operator.
Returns
-------
numpy.ndarray
The real part of :func:`operator_admittance`.
"""
return np.real(operator_admittance(tables))
[docs]
def operator_admittance(
tables: OperatorTables,
) -> Complex[np.ndarray, "n_y n_x n_omega"]:
"""Return the axial admittance of the operator's medium at every element.
:func:`pnps.flux.axial_admittance` of the tables' wavenumber, zero off the
operator's hard band limit when it has one.
Parameters
----------
tables : OperatorTables
The operator.
Returns
-------
numpy.ndarray
The complex admittance, ``(n_y, n_x, n_omega)``.
"""
y = axial_admittance(
tables.k2[None, None, :], tables.kperp2[:, :, None], tables.omega[None, None, :]
)
if tables.active is not None:
y = np.where(tables.active[None, None, :], y, 0.0)
return y
[docs]
def time_edge_fraction(
e: Complex[np.ndarray, "n_y n_x n_omega"], edge_fraction: float = 0.05
) -> float:
"""Return the fraction of total energy in the outer edges of the time window.
Only a 1-D inverse FFT along the frequency axis is needed (Parseval over the
transverse axes). Time index 0 is ``t = -T/2``, so the window edges are the first
and last bins.
Parameters
----------
e : numpy.ndarray
Spectral state ``(n, n, nt)``.
edge_fraction : float
Fraction of the window counted as edge, split between the two ends.
Returns
-------
float
Energy fraction in the edges.
"""
n_edge = max(1, int(e.shape[-1] * edge_fraction / 2))
p_t = np.sum(np.abs(np.fft.ifft(e, axis=-1)) ** 2, axis=(0, 1))
return float((p_t[:n_edge].sum() + p_t[-n_edge:].sum()) / p_t.sum())