# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Form the delayed input state on the fly, with no stored beamlets.
The input of one delay point is the gate pair plus the delay-phased test arm (or, in
the self-diffraction layout, the probe plus the delay-phased gate; see
:mod:`pnps.geometry`), each the
separable illumination (a transverse far-field profile times the 1-D pulse spectrum,
normalised once) cut by one chromatic hole and carried into the slab at constant axial
flux (:func:`pnps.flux.launch_factor`). Nothing about it is intrinsically 3-D, so
it is never stored: :func:`form_input` evaluates the hole transmissions per
element and writes the superposed state straight into the output array, and
:func:`beamlet_diagnostics` computes the beamlet spectra and the delivered energy a
scan file records, in one pass and without a field-sized buffer.
The reference rendering, which materialises the three arms with NumPy, is
:func:`pnps.beams.build_beamlet_fields` (with :func:`pnps.beams.beamlets_from_fields`);
the two agree to rounding.
The result is handed to solprop verbatim: both codes store the unnormalised DFT in
the same sign convention, and solprop's Cartesian column index ``ix + n_x * iy`` is
exactly the C-order flattening of this package's ``[iy, ix]`` axes, so the state
``(n, n, nt)`` reshapes without a copy to solprop's ``(n * n, 1, nt)``.
"""
from collections.abc import Collection
from dataclasses import dataclass
from typing import Literal, no_type_check
import numpy as np
from jaxtyping import Complex, Float
from numba import njit, prange
from pnps.beams import (
Beam,
Beamlets,
illumination_scale,
transverse_factor,
)
from pnps.exceptions import InstrumentError
from pnps.geometry import input_layout
from pnps.grids import SpaceGrid, TimeGrid
from pnps.kernels import admittance, apod_code, hole_weight, launch_weight
from pnps.observables import mapping_factor
from pnps.pulse import energy_prefactor
__all__ = [
"ARMS",
"InputFormer",
"beamlet_diagnostics",
"build_input_former",
"form_arm",
"form_input",
]
#: The three beamlets, in the order the former sums them: the two gates (which
#: share the delay-free phase) and the test arm (which carries the delay). The
#: self-diffraction layout puts its probe in the first slot and its gate in the last,
#: and has no second gate.
ARMS = ("gate1", "gate2", "test")
@njit(parallel=True, cache=True)
@no_type_check
def _form_input( # noqa: PLR0913, PLR0917 - a numba kernel takes its buffers positionally
e: Complex[np.ndarray, "n_y n_x n_omega"],
transverse: Complex[np.ndarray, "n_y n_x"],
e_omega: Complex[np.ndarray, " n_omega"],
scale: float,
kx: Float[np.ndarray, " n_x"],
omega: Float[np.ndarray, " n_omega"],
k2: Complex[np.ndarray, " n_omega"],
factor: Float[np.ndarray, " n_omega"],
phase: Complex[np.ndarray, " n_omega"],
delta_k: float,
holes: Float[np.ndarray, "n_arms 2"],
mask_diam: float,
apod_code: int,
apod_param: float,
sub: int,
weights: Float[np.ndarray, " n_arms"],
) -> None:
"""Form the delayed input state directly into ``e``.
The gates share a delay and are summed first, matching
:func:`pnps.beams.build_beamlet_fields`; the test arm carries ``phase``. ``weights``
selects arms (1.0 or 0.0 each; a multiply by 1.0 is exact, so the full input is
bit-identical to an unweighted sum). Non-positive frequencies get zero, where the
angle-to-position mapping diverges. Each element is carried into the slab by
:func:`pnps.kernels.launch_weight`.
Parameters
----------
e : numpy.ndarray
Output state ``E[n_y, n_x, n_omega]``, complex128, overwritten.
transverse : numpy.ndarray
Transverse factor ``(n_y, n_x)`` complex, indexed ``[iy, ix]``.
e_omega : numpy.ndarray
Band-limited 1-D input spectrum ``(n_omega,)`` complex.
scale : float
Real factor normalising ``transverse * e_omega`` to the pre-mask energy.
kx : numpy.ndarray
Momentum axis shared by x and y, ``(n_x,)``, rad/m.
omega : numpy.ndarray
Absolute angular frequency, ``(n_omega,)``, rad/s.
k2 : numpy.ndarray
The slab's material wavenumber squared, ``(n_omega,)``, complex.
factor : numpy.ndarray
Angle-to-position mapping ``f_foc c / omega`` of the input holes,
``(n_omega,)`` in m/(rad/m), zero at non-positive frequencies.
phase : numpy.ndarray
Delay phase ``exp(1j omega tau)`` of the test arm, ``(n_omega,)`` complex.
delta_k : float
Momentum pixel pitch, rad/m.
holes : numpy.ndarray
Hole centres ``(3, 2)`` in the mask plane, m: gate 1, gate 2, test.
mask_diam : float
Hole diameter, m.
apod_code : int
Edge-profile code (:data:`pnps.kernels.APOD_CODES`).
apod_param : float
Edge parameter.
sub : int
Supersampling factor of the ``"area"`` rendering (1 otherwise).
weights : numpy.ndarray
Arm weights ``(3,)`` (gate 1, gate 2, test), each 1.0 or 0.0.
"""
ny, nx, nt = e.shape
for iy in prange(ny):
t = transverse[iy]
for ix in range(nx):
base_xy = t[ix]
kp2 = kx[ix] * kx[ix] + kx[iy] * kx[iy]
for k in range(nt):
f = factor[k]
if f == 0.0:
e[iy, ix, k] = 0.0 + 0.0j
continue
base = (base_xy * e_omega[k]) * scale
base = base * launch_weight(k2[k], kp2, omega[k])
m_g1 = hole_weight(
kx[ix], kx[iy], f, delta_k, delta_k,
holes[0, 0], holes[0, 1], mask_diam, apod_code, apod_param, sub,
) # fmt: skip
m_g2 = hole_weight(
kx[ix], kx[iy], f, delta_k, delta_k,
holes[1, 0], holes[1, 1], mask_diam, apod_code, apod_param, sub,
) # fmt: skip
m_test = hole_weight(
kx[ix], kx[iy], f, delta_k, delta_k,
holes[2, 0], holes[2, 1], mask_diam, apod_code, apod_param, sub,
) # fmt: skip
e[iy, ix, k] = (
base * (m_g1 * weights[0]) + base * (m_g2 * weights[1])
) + (base * (m_test * weights[2])) * phase[k]
@njit(parallel=True, cache=True)
@no_type_check
def _beamlet_partials( # noqa: PLR0913, PLR0917 - a numba kernel takes its buffers positionally
transverse: Complex[np.ndarray, "n_y n_x"],
e_omega: Complex[np.ndarray, " n_omega"],
scale: float,
kx: Float[np.ndarray, " n_x"],
omega: Float[np.ndarray, " n_omega"],
k2: Complex[np.ndarray, " n_omega"],
factor: Float[np.ndarray, " n_omega"],
delta_k: float,
holes: Float[np.ndarray, "n_arms 2"],
mask_diam: float,
apod_code: int,
apod_param: float,
sub: int,
weights: Float[np.ndarray, " n_arms"],
partial: Float[np.ndarray, "n_rows 7 n_omega"],
) -> None:
"""Accumulate, per transverse row, the beamlet spectra and arm energies.
``partial[iy]`` is ``(7, nt)``: ``eta |E_g1|^2``, the signed on-axis sum of ``E_g1``
(real, imaginary), the same sum of its closure ``conj(y) E_g1`` (real, imaginary),
``eta |E_g1 + E_g2|^2`` and ``eta |E_test|^2``, each summed over ``ix``, with ``y``
the admittance and ``eta`` its real part. The arms are formed and weighted exactly
as :func:`_form_input` does.
Parameters
----------
transverse : numpy.ndarray
Transverse factor ``(n_y, n_x)`` complex, indexed ``[iy, ix]``.
e_omega : numpy.ndarray
Band-limited 1-D input spectrum ``(n_omega,)`` complex.
scale : float
Real factor normalising ``transverse * e_omega`` to the pre-mask energy.
kx : numpy.ndarray
Momentum axis shared by x and y, ``(n_x,)``, rad/m.
omega : numpy.ndarray
Absolute angular frequency, ``(n_omega,)``, rad/s.
k2 : numpy.ndarray
The slab's material wavenumber squared, ``(n_omega,)``, complex.
factor : numpy.ndarray
Angle-to-position mapping ``f_foc c / omega`` of the input holes,
``(n_omega,)`` in m/(rad/m), zero at non-positive frequencies.
delta_k : float
Momentum pixel pitch, rad/m.
holes : numpy.ndarray
Hole centres ``(3, 2)`` in the mask plane, m: gate 1, gate 2, test.
mask_diam : float
Hole diameter, m.
apod_code : int
Edge-profile code (:data:`pnps.kernels.APOD_CODES`).
apod_param : float
Edge parameter.
sub : int
Supersampling factor of the ``"area"`` rendering (1 otherwise).
weights : numpy.ndarray
Arm weights ``(3,)`` (gate 1, gate 2, test), each 1.0 or 0.0.
partial : numpy.ndarray
Output ``(n_y, 7, n_omega)`` real, overwritten row by row.
"""
ny, nx = transverse.shape
nt = e_omega.shape[0]
for iy in prange(ny):
part = partial[iy]
part[:, :] = 0.0
t = transverse[iy]
for ix in range(nx):
base_xy = t[ix]
sign = 1.0 if ((iy + ix) & 1) == 0 else -1.0
kp2 = kx[ix] * kx[ix] + kx[iy] * kx[iy]
for k in range(nt):
f = factor[k]
if f == 0.0:
continue
base = (base_xy * e_omega[k]) * scale
base = base * launch_weight(k2[k], kp2, omega[k])
y = admittance(k2[k], kp2, omega[k])
y_re, y_im = y.real, y.imag
m_g1 = hole_weight(
kx[ix], kx[iy], f, delta_k, delta_k,
holes[0, 0], holes[0, 1], mask_diam, apod_code, apod_param, sub,
) # fmt: skip
m_g2 = hole_weight(
kx[ix], kx[iy], f, delta_k, delta_k,
holes[1, 0], holes[1, 1], mask_diam, apod_code, apod_param, sub,
) # fmt: skip
m_test = hole_weight(
kx[ix], kx[iy], f, delta_k, delta_k,
holes[2, 0], holes[2, 1], mask_diam, apod_code, apod_param, sub,
) # fmt: skip
g1 = base * (m_g1 * weights[0])
g12 = g1 + base * (m_g2 * weights[1])
test = base * (m_test * weights[2])
part[0, k] += y_re * (g1.real * g1.real + g1.imag * g1.imag)
part[1, k] += sign * g1.real
part[2, k] += sign * g1.imag
part[3, k] += sign * (y_re * g1.real + y_im * g1.imag)
part[4, k] += sign * (y_re * g1.imag - y_im * g1.real)
part[5, k] += y_re * (g12.real * g12.real + g12.imag * g12.imag)
part[6, k] += y_re * (test.real * test.real + test.imag * test.imag)
def _checked_out(
former: InputFormer, out: Complex[np.ndarray, "n_y n_x n_omega"] | None
) -> Complex[np.ndarray, "n_y n_x n_omega"]:
"""Return ``out`` after checking it, or a fresh state array.
Parameters
----------
former : InputFormer
The configuration's input tables, which fix the state shape.
out : numpy.ndarray or None
A C-contiguous complex128 ``(n_y, n_x, n_omega)`` array, or None to
allocate one.
Returns
-------
numpy.ndarray
``out``, or a new uninitialised complex128 state array.
Raises
------
InstrumentError
If ``out`` has the wrong shape, type or layout.
"""
if out is None:
return np.empty(former.shape, dtype=np.complex128)
if (
out.shape != former.shape
or out.dtype != np.complex128
or not out.flags.c_contiguous
):
raise InstrumentError(
f"out must be a C-contiguous complex128 array of shape {former.shape}"
)
return out
def _form(
former: InputFormer,
tau: float,
weights: Float[np.ndarray, " n_arms"],
out: Complex[np.ndarray, "n_y n_x n_omega"] | None,
) -> Complex[np.ndarray, "n_y n_x n_omega"]:
"""Run the former kernel with the given arm weights.
Parameters
----------
former : InputFormer
The configuration's input tables.
tau : float
Delay of the test arm in s.
weights : numpy.ndarray
Arm weights ``(3,)`` (gate 1, gate 2, test), each 1.0 or 0.0, applied on top
of the layout's own.
out : numpy.ndarray or None
A C-contiguous complex128 ``(n_y, n_x, n_omega)`` array to write into,
or None to allocate one.
Returns
-------
numpy.ndarray
The state ``E[n_y, n_x, n_omega]``, complex128 (``out`` when given).
Raises
------
InstrumentError
If ``out`` has the wrong shape, type or layout.
"""
out = _checked_out(former, out)
phase = np.exp(1j * former.omega * float(tau))
_form_input(
out, former.transverse, former.e_omega, former.scale, former.kx,
former.omega, former.k2, former.factor, phase, former.delta_k,
former.holes, former.mask_diam, former.apod_code, former.apod_param,
former.sub, weights * former.weights,
) # fmt: skip
return out
def _arm_weights(
former: InputFormer, arms: Collection[str] | None
) -> Float[np.ndarray, " n_arms"]:
"""Return the former's weights selecting ``arms``, all ones for None.
Raises
------
InstrumentError
If ``arms`` is empty, names an unknown arm, or one the layout lacks.
"""
if arms is None:
return np.ones(len(ARMS))
chosen = set(arms)
if not chosen:
raise InstrumentError("arms is empty: name at least one of the beamlets")
if unknown := chosen - set(ARMS):
raise InstrumentError(f"arms must be among {ARMS}, got {sorted(unknown)}")
if absent := [a for a in ARMS if a in chosen and not former.weights[ARMS.index(a)]]:
raise InstrumentError(f"this beam layout has no {absent[0]!r} arm")
return np.array([1.0 if name in chosen else 0.0 for name in ARMS])
[docs]
def beamlet_diagnostics(
former: InputFormer, tgrid: TimeGrid, sgrid: SpaceGrid
) -> Beamlets:
"""Compute the beamlet spectra and the delivered energy in one pass.
Each is measured as the run's observables are, by the slab's axial flux.
Parameters
----------
former : InputFormer
The configuration's input tables.
tgrid, sgrid : TimeGrid, SpaceGrid
The simulation grids.
Returns
-------
Beamlets
The gate-1 beamlet's (the self-diffraction probe's) k-integrated and on-axis
spectra, and the delivered energy of all the arms.
"""
n, _, nt = former.shape
partial = np.zeros((n, 7, nt))
_beamlet_partials(
former.transverse, former.e_omega, former.scale, former.kx, former.omega,
former.k2, former.factor, former.delta_k, former.holes,
former.mask_diam, former.apod_code, former.apod_param, former.sub,
former.weights, partial,
) # fmt: skip
# Rows summed in index order: deterministic whatever the thread count.
totals = partial.sum(axis=0)
prefactor = energy_prefactor(tgrid, sgrid)
return Beamlets(
i_omega_beamlet=totals[0] / n**2,
# The on-axis amplitude paired with its closure, Re(A conj(G)).
i_omega_beamlet_reimaged=(totals[1] * totals[3] + totals[2] * totals[4]) / n**4,
delivered_energy=prefactor * float(totals[5].sum())
+ prefactor * float(totals[6].sum()),
)