# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""The per-delay-point simulation driver.
One delay point is: form the superposed gate pair and delay-phased test beamlet
(:mod:`pnps.form_input`), let solprop propagate the 3-D envelope UPPE through the slab
on a replayed fixed schedule (:mod:`pnps.bridge`), and at every save position reduce
the state on the host to the per-window spectra (:mod:`pnps.reduce_numba`). One
bridge serves every delay point of a configuration: :func:`run_delay_point` takes a
built bridge, :func:`simulate_delay_point` builds and closes one around a single
point.
The delay convention is "gate": the test (probe) beamlet is multiplied by
``exp(+1j omega tau)`` (advanced by tau), equivalent to delaying the gate pair by
``+tau``. Downstream readers must not reverse the delay axis.
"""
from collections.abc import Callable
import numpy as np
from jaxtyping import Complex, Float
from pnps.absorber import WRAP_COUPLING_LIMIT, lap_lost, wrap_coupling
from pnps.bridge import Bridge, bridge_tables, build_bridge
from pnps.exceptions import ConfigError, DelayError
from pnps.form_input import (
form_input,
)
from pnps.reference import apply_linear
from pnps.setup import Setup
__all__ = [
"DIAGNOSTICS",
"OBSERVABLES",
"SPECTRAL_DIAGNOSTICS",
"NonlinearVisitor",
"delayed_input",
"run_delay_point",
"simulate_delay_point",
"visit_nonlinear",
]
#: A visitor of :func:`visit_nonlinear`: the position in m, the field there and its
#: nonlinear part, each ``(n, n, nt)`` and valid only during the call.
NonlinearVisitor = Callable[
[
float,
Complex[np.ndarray, "n_y n_x n_omega"],
Complex[np.ndarray, "n_y n_x n_omega"],
],
None,
]
#: The per-window and signal-region spectra every save position yields.
OBSERVABLES = ("i_omega_win", "i_omega_reimaged", "i_omega_full")
#: The per-save spectral diagnostics: the whole beam's spectrum.
SPECTRAL_DIAGNOSTICS = ("i_omega_beam",)
#: The per-save scalar diagnostics.
DIAGNOSTICS = (
"energy",
"absorb_omega",
"absorb_lap",
"absorb_k",
"gd_band_power",
"alias_fraction",
"edge_fraction",
)
def _check_delay(setup: Setup, tau: float | Float[np.ndarray, "*shape"]) -> None:
"""Refuse a non-scalar delay, or one where light that wraps the window could act.
A delay is admitted when ``|tau| <= 0.75 * time_headroom`` (the rule the absorber
was laid out by: the pulses then sit inside the protected region, and light can
reach them through the wrap only where the lap budget is at full strength), or
when the wrap coupling of :func:`pnps.absorber.wrap_coupling` is at most
:data:`pnps.absorber.WRAP_COUPLING_LIMIT`. The check reads the configuration's
absorber and input; it changes neither.
Parameters
----------
setup : Setup
The configuration: its window, absorber, slab and input spectrum bound the
delay.
tau : float or numpy.ndarray
The delay in s, as the caller gave it: anything but a scalar is refused.
Raises
------
DelayError
If ``tau`` is not a scalar.
ConfigError
If ``|tau|`` exceeds 75 % of the protected time headroom and the wrap
coupling exceeds its limit.
"""
if np.ndim(tau) != 0:
raise DelayError(
"tau must be one delay: solprop steps one delay point at a time "
"(it refuses spatial lockstep batches), so scan delays in a loop "
"over one bridge (pnps.scan.run_scan does)"
)
delay = abs(float(tau))
headroom = setup.cfg.time_headroom
if delay <= 0.75 * headroom:
return
coupling = wrap_coupling(
setup.tgrid,
setup.cfg.thickness,
setup.gamma_omega,
setup.e_omega_input,
delay,
)
if coupling > WRAP_COUPLING_LIMIT:
raise ConfigError(
f"|tau| = {delay:.3g} s exceeds 75% of time_headroom ({headroom:.3g} s), "
f"and light that wraps the {setup.tgrid.nt * setup.tgrid.delta_t:.3g} s "
f"window could drive {coupling:.2g} of the input's peak nonlinear "
f"polarization at the other pulse (limit {WRAP_COUPLING_LIMIT:.0e}; "
"pnps.absorber.wrap_coupling). Increase Config.time_headroom, so that the "
"lap budget absorbs the wrapping light sooner (and trange to keep the "
"band), or shorten the delay range."
)
[docs]
def run_delay_point(bridge: Bridge, tau: float) -> dict[str, Float[np.ndarray, "*_"]]:
"""Simulate one delay point on a built bridge and extract all observables.
Correctness guards: light that wraps the periodic time window must not reach
the other pulse strongly enough to act there (the delay lies within 75 % of
``time_headroom``, or its wrap coupling is within
:data:`pnps.absorber.WRAP_COUPLING_LIMIT`; :func:`pnps.absorber.wrap_coupling`),
and the total field energy must never grow (the propagation is
lossy-or-conservative by construction, so growth means numerical trouble).
Per-save diagnostics report what the absorbers remove and how much field power
sits in the group-delay-absorbed band.
Parameters
----------
bridge : Bridge
The configuration on solprop (:func:`pnps.bridge.build_bridge`).
tau : float
The delay in s.
Returns
-------
dict of numpy.ndarray
``i_omega_win`` and ``i_omega_reimaged`` with shape
``(nz, n_windows, nt)``, ``i_omega_full`` and ``i_omega_beam`` with
``(nz, nt)``, ``z``, the per-save diagnostics of :data:`DIAGNOSTICS` with
shape ``(nz,)``, and ``lap_lost`` with ``(nt,)``: the energy per bin the lap
budget removed between the first and the last save position
(:func:`pnps.absorber.lap_lost`; include 0.0 in ``zsave`` to cover the whole
slab, and :func:`pnps.absorber.lap_loss_share` turns it into a band's
share). The spectra are in the state's unnormalised-DFT units (scaling as
the fourth power of the transverse sample count at fixed extent).
Raises
------
DelayError
If ``tau`` is not a scalar.
ConfigError
If light that wraps the time window could act at the delay
(:func:`pnps.absorber.wrap_coupling`).
EngineError
If the field energy grows during propagation.
"""
setup = bridge.setup
_check_delay(setup, tau)
zsave = bridge.zsave
n_z, n_win, nt = len(zsave), len(setup.windows), setup.tgrid.nt
out: dict[str, Float[np.ndarray, "*_"]] = {
"i_omega_win": np.zeros((n_z, n_win, nt)),
"i_omega_reimaged": np.zeros((n_z, n_win, nt)),
"i_omega_full": np.zeros((n_z, nt)),
"i_omega_beam": np.zeros((n_z, nt)),
**{key: np.zeros(n_z) for key in DIAGNOSTICS},
}
# The formed input is passed without a name, so nothing here holds it: solprop
# copies it into its state and lets it go. Each plane is reduced as it is
# reached (on the host, or by solprop's statistics), so only the reductions are
# kept, and the bridge stops the run if the energy grows.
planes = bridge.observations(delayed_input(setup, float(tau)), tau=float(tau))
for iz, (_, obs) in enumerate(planes):
for key in (*OBSERVABLES, *SPECTRAL_DIAGNOSTICS, *DIAGNOSTICS):
out[key][iz] = getattr(obs, key)
out["z"] = zsave.copy()
out["lap_lost"] = lap_lost(
out["i_omega_beam"], zsave, setup.gamma_omega, setup.gamma_lap
)
return out
[docs]
def simulate_delay_point(
setup: Setup,
tau: float,
zsave: Float[np.ndarray, " n_z"],
*,
h_target: float,
backend: str = "auto",
) -> dict[str, Float[np.ndarray, "*_"]]:
"""Simulate one delay point and extract all observables.
Builds a bridge, runs :func:`run_delay_point` and closes it. Building a
bridge translates the problem and allocates the solprop backend, so a scan
builds one and reuses it (:func:`pnps.scan.run_scan`).
Parameters
----------
setup : Setup
The configuration, as built by :func:`~pnps.setup.build_setup`.
tau : float
One delay in s.
zsave : numpy.ndarray
Strictly increasing save positions in m; include 0.0 to record the
input. Every positive position is an edge of the replayed schedule.
h_target : float
Largest step in m. Choose it with :mod:`pnps.calibrate`.
backend : str
The solprop backend registry name (``"auto"``, which is
``"native"``; ``"native"``; ``"numpy_ref"``).
Returns
-------
dict of numpy.ndarray
See :func:`run_delay_point`.
Raises
------
DelayError
If ``tau`` is not a scalar.
ConfigError
If light that wraps the time window could act at the delay
(:func:`pnps.absorber.wrap_coupling`), or the save positions are invalid.
EngineError
If the field energy grows during propagation.
"""
_check_delay(setup, tau)
with build_bridge(setup, zsave, h_target, backend=backend) as bridge:
return run_delay_point(bridge, tau)
[docs]
def visit_nonlinear(bridge: Bridge, tau: float, visitor: NonlinearVisitor) -> None:
"""Propagate one delay point and hand each plane on with its nonlinear part.
The nonlinear part is ``N(z) = E(z) - exp(L z) E(0)``: the field minus the input
carried by the configured linear operator alone (:func:`pnps.bridge.bridge_tables`
with :func:`pnps.reference.apply_linear`, the operator solprop applies, equal to
its march to about 1e-12 of the peak; ``tests/test_ladder.py``, rung (i)). It is
everything the nonlinear polarisation has generated: the four-wave-mixing signal
and the Kerr changes of the arms. Linear propagation in the homogeneous slab keeps
each component's transverse wavevector, so wherever the input is exactly zero in
momentum, such as a signal window behind compact input holes, ``N`` is the field
itself.
The planes are streamed (:meth:`pnps.bridge.Bridge.visit`): the input and one plane
with its nonlinear part are held at a time, three field volumes.
Parameters
----------
bridge : Bridge
The configuration on solprop, with ``reduction="host"``.
tau : float
The delay in s.
visitor : callable
Called at every save position with the position in m, the field and its
nonlinear part, each ``(n, n, nt)``; both arrays are reused after the call.
Raises
------
ConfigError
If light that wraps the time window could act at the delay
(:func:`pnps.absorber.wrap_coupling`).
DelayError
If ``tau`` is not a scalar.
EngineError
If the bridge reduces with solprop's statistics.
"""
setup = bridge.setup
_check_delay(setup, tau)
e0 = delayed_input(setup, float(tau))
tables = bridge_tables(bridge)
def visit(z: float, field: Complex[np.ndarray, "n_y n_x n_omega"]) -> None:
"""Subtract the linearly propagated input and hand both on.
Parameters
----------
z : float
The position, m.
field : numpy.ndarray
The field there.
"""
visitor(z, field, field - apply_linear(e0, tables, z))
# The bridge marches a copy: e0 itself is kept for the subtraction.
bridge.visit(e0.copy(), visit, tau=float(tau))