Source code for pnps.form_input

# 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")


[docs] @dataclass(frozen=True) class InputFormer: """The separable tables that define the input state; nothing field-sized. Built once per configuration by :func:`build_input_former`. Attributes ---------- transverse : numpy.ndarray Transverse factor of the unmasked beam, ``(n, n)`` complex, indexed ``[iy, ix]`` (:func:`pnps.beams.transverse_factor`). e_omega : numpy.ndarray Band-limited 1-D input spectrum, ``(nt,)`` complex. scale : float Real factor normalising ``transverse * e_omega`` to the pre-mask energy. kx : numpy.ndarray Momentum axis shared by x and y, rad/m. omega : numpy.ndarray Absolute angular frequency, FFT-ordered, rad/s. k2 : numpy.ndarray The slab's material wavenumber squared ``(n omega / c)^2``, ``(nt,)``, complex, rad^2/m^2, zero off the band. factor : numpy.ndarray Angle-to-position mapping ``f_foc c / omega`` of the input holes, 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, for gate 1, gate 2 and the test arm (:func:`pnps.geometry.input_layout`). weights : numpy.ndarray Arm weights ``(3,)``, each 1.0 or 0.0; an arm of weight zero is not part of the layout. 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). """ 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"] weights: Float[np.ndarray, " n_arms"] mask_diam: float apod_code: int apod_param: float sub: int
[docs] @property def shape(self) -> tuple[int, int, int]: """The state shape ``(n, n, nt)``. Returns ------- tuple of int ``(n_y, n_x, n_omega)``. """ n = len(self.kx) return (n, n, len(self.omega))
[docs] def build_input_former( # noqa: PLR0913, PLR0917 - grids, beam, mask and pulse tgrid: TimeGrid, sgrid: SpaceGrid, beam: Beam, e_omega: Complex[np.ndarray, " n_omega"], energy: float, mask_diam: float, mask_spacing: float, apod: str, apod_param: float, geometry: str = "tg", *, k2: Complex[np.ndarray, " n_omega"], ) -> InputFormer: """Build the tables of the input former. Parameters ---------- tgrid, sgrid : TimeGrid, SpaceGrid The simulation grids. beam : HE11Beam, GaussianBeam or UniformBeam Input beam geometry. e_omega : numpy.ndarray Band-limited 1-D input spectrum on ``tgrid.omega`` (arbitrary scale). energy : float Pre-mask pulse energy (all arms together), J. mask_diam, mask_spacing : float Hole diameter and edge-to-edge spacing in m. apod : str Input-hole edge profile, see :func:`pnps.beams.chromatic_mask`. apod_param : float Input-hole edge parameter. geometry : {"tg", "sd"}, optional The beam layout (:mod:`pnps.geometry`). k2 : numpy.ndarray The slab's material wavenumber squared, ``(nt,)``, complex, zero off the band (:func:`pnps.materials.silica_k2`). Returns ------- InputFormer The separable tables of the input state. Raises ------ InstrumentError For an unknown edge profile. ConfigError For an unknown layout. """ transverse = np.ascontiguousarray(transverse_factor(sgrid, beam)) spectrum = np.ascontiguousarray(np.asarray(e_omega, dtype=complex)) layout = input_layout(geometry, mask_diam, mask_spacing) omega = np.ascontiguousarray(tgrid.omega, dtype=float) return InputFormer( transverse=transverse, e_omega=spectrum, scale=illumination_scale(tgrid, sgrid, transverse, spectrum, energy), kx=np.ascontiguousarray(sgrid.kx, dtype=float), omega=omega, k2=np.ascontiguousarray(k2, dtype=complex), factor=mapping_factor(omega, float(beam.f_foc)), delta_k=float(sgrid.kx[1] - sgrid.kx[0]), # Gate 1, gate 2, then the test arm; the gates are summed first. holes=layout.holes, weights=layout.weights, mask_diam=float(mask_diam), apod_code=apod_code(apod), apod_param=float(apod_param), sub=round(apod_param) if apod == "area" else 1, )
@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
[docs] def form_input( former: InputFormer, tau: float, out: Complex[np.ndarray, "n_y n_x n_omega"] | None = None, *, arms: Collection[str] | None = None, ) -> Complex[np.ndarray, "n_y n_x n_omega"]: """Form the input state of one delay point. The test arm is advanced by ``tau`` (``exp(+1j omega tau)``, the "gate" delay convention); the gate pair is delay-free. In the self-diffraction layout the gate is advanced and the probe is delay-free. Parameters ---------- former : InputFormer The configuration's input tables. tau : float Delay in s. out : numpy.ndarray or None A C-contiguous complex128 ``(n, n, nt)`` array to write into, or None to allocate one. arms : collection of str or None, optional Form only these beamlets (names from :data:`ARMS`), each exactly as it is in the whole input, for a separation over the arms (:mod:`pnps.separation`); None forms every arm of the layout. Returns ------- numpy.ndarray The state ``(n, n, nt)``, complex128, C-contiguous (``out`` when given). Raises ------ InstrumentError If ``out`` has the wrong shape, type or layout, or ``arms`` is empty or names an unknown arm or one the layout does not have. Examples -------- >>> from pnps.form_input import ARMS >>> sorted(ARMS) ['gate1', 'gate2', 'test'] """ return _form(former, tau, _arm_weights(former, arms), 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 form_arm( former: InputFormer, arm: Literal["gate1", "gate2", "test"], out: Complex[np.ndarray, "n_y n_x n_omega"] | None = None, ) -> Complex[np.ndarray, "n_y n_x n_omega"]: """Form one beamlet alone, at zero delay. For diagnostics of the input (its focal spot, its edge, its coverage of the grid); a run forms the superposed input with :func:`form_input`. Parameters ---------- former : InputFormer The configuration's input tables. arm : {"gate1", "gate2", "test"} Which beamlet (see :data:`ARMS`). out : numpy.ndarray or None A C-contiguous complex128 ``(n, n, nt)`` array to write into, or None to allocate one. Returns ------- numpy.ndarray The beamlet ``(n, n, nt)``, complex128, C-contiguous. Raises ------ InstrumentError For an unknown arm, an arm the layout does not have, or an ``out`` of the wrong shape, type or layout. """ if arm not in ARMS: raise InstrumentError(f"arm must be one of {ARMS}, got {arm!r}") return _form(former, 0.0, _arm_weights(former, (arm,)), out)
[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()), )