Source code for pnps.observables

# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later

"""What one save plane yields, and the slot layout of the fused reduction that fills it.

solprop propagates the field and hands back each saved plane (:mod:`pnps.bridge`);
this package reduces the plane on the host to the measured spectra and the
diagnostics, in one traversal of the state (:mod:`pnps.reduce_numba`). That traversal
fills an agreed set of accumulators -- the *slots* below -- and
:func:`assemble_observation` turns them into the :class:`Observation` the driver
records. The collection windows must be holes in a single mask, so the mask-plane
radius is computed once per element and shared across them
(:func:`check_windows_share_a_mask`).

Everything here is in the state's units: the unnormalised 3-D DFT of the field in V/m,
so the spectra scale as the fourth power of the transverse sample count at fixed
extent, and ``energy_prefactor`` converts summed ``eta |E|^2`` to joules. Every sum is
weighted by the medium's axial admittance ``eta`` (:mod:`pnps.flux`).
"""

from collections.abc import Sequence
from typing import NamedTuple

import numpy as np
from jaxtyping import Float
from scipy.constants import c

from pnps.exceptions import ReductionError
from pnps.extraction import WindowSpec

__all__ = [
    "N_SHARED_SLOTS",
    "SLOTS_PER_WINDOW",
    "SLOT_ABSORB_K",
    "SLOT_INNER",
    "SLOT_POWER",
    "SLOT_REGION",
    "Observation",
    "assemble_observation",
    "check_windows_share_a_mask",
    "inner_half_width",
    "mapping_factor",
    "n_slots",
]

# --- The fused reduction's slot layout ----------------------------------
#
# Five shared accumulators, then five per collection window. Each weights |E|^2 by
# the admittance eta.
# Per frequency: the beam's spectrum (from which the energy and every spectral rate's
# absorption follow, those rates depending on frequency alone), the signal region's,
# and the transverse ramp's absorption, which depends on the column.
SLOT_POWER = 0  # sum eta |E|^2 over the columns: the beam's spectrum
SLOT_REGION = 1  # the same over the signal region only (pnps.geometry)
SLOT_ABSORB_K = 2  # gamma_k eta |E|^2, the transverse-wavevector ramp's rate
SLOT_INNER = 3  # eta |E|^2 inside the inner box, half the momentum span (aliasing)
N_SHARED_SLOTS = 4
# Collected energy; Re and Im of the on-axis sum A; Re and Im of its magnetic closure
# G, the same sum with each element weighted by the conjugate admittance.
SLOTS_PER_WINDOW = 5


[docs] class Observation(NamedTuple): """Everything one save plane yields, as host values. Attributes ---------- i_omega_win : numpy.ndarray Windowed spectra, ``(n_windows, nt)``. i_omega_reimaged : numpy.ndarray On-axis re-imaged spectra, ``(n_windows, nt)``: the same-frequency pairing ``Re(A conj(G))`` of the on-axis amplitude with its magnetic closure. i_omega_full : numpy.ndarray Un-windowed spectrum of the signal region (:mod:`pnps.geometry`), ``(nt,)``. i_omega_beam : numpy.ndarray Spectrum of the whole beam, every column, ``(nt,)``, in the units of ``i_omega_full``. energy : float Pulse energy in J: the axial flux through the plane. absorb_omega, absorb_lap, absorb_k : float Instantaneous measured absorption rates of the three loss channels: the band edges' spectral absorber, the group-delay lap budget and the transverse-wavevector ramp. gd_band_power : float Fraction of the energy in the group-delay-absorbed bins. alias_fraction : float Fraction of the energy outside the inner momentum box, half of each axis's largest wavenumber (:func:`pnps.statistics.inner_box_region`): where a cubic product of the field can fold back into its own band. edge_fraction : float Fraction of energy in the outer 5 % of the time window, or NaN when the diagnostic was not requested (``Config.edge_diagnostic``). """ i_omega_win: Float[np.ndarray, "n_windows n_omega"] i_omega_reimaged: Float[np.ndarray, "n_windows n_omega"] i_omega_full: Float[np.ndarray, " n_omega"] i_omega_beam: Float[np.ndarray, " n_omega"] energy: float absorb_omega: float absorb_lap: float absorb_k: float gd_band_power: float alias_fraction: float edge_fraction: float
[docs] def n_slots(n_windows: int) -> int: """Return the accumulators the fused reduction needs for ``n_windows`` windows. Parameters ---------- n_windows : int Collection windows. Returns ------- int Slot count. Examples -------- >>> n_slots(6) 34 """ return N_SHARED_SLOTS + SLOTS_PER_WINDOW * n_windows
[docs] def inner_half_width(kx: Float[np.ndarray, " n_x"], fraction: float = 0.5) -> float: """Return the half-width of the momentum box the aliasing reading counts inside. A cubic product of a band ``|k| <= K`` reaches ``3K`` and is stored at ``3K - 2 k_max``, inside the band once ``K >= k_max / 2`` (solprop's Cartesian guide, "Reading the risk of aliasing"). So the box is ``fraction`` of the largest stored wavenumber, half a sample short, so that a column on the limit counts as outside and none sits on the box's half-open edges. Parameters ---------- kx : numpy.ndarray The stored momentum axis, shared by x and y, rad/m. fraction : float, optional The box's share of the largest wavenumber: 1/2 for cubic products. Returns ------- float The half-width, rad/m. Examples -------- >>> import numpy as np >>> inner_half_width(2 * np.pi * np.fft.fftfreq(8, 1.0 / 8)) 9.42477796076938 """ kx = np.asarray(kx, dtype=float) return fraction * float(np.max(np.abs(kx))) - 0.5 * abs(float(kx[1] - kx[0]))
[docs] def mapping_factor( omega: Float[np.ndarray, " n_omega"], zmask: float, achromatic_wavelength: float | None = None, ) -> Float[np.ndarray, " n_omega"]: """Return the angle-to-position mapping ``zmask c / omega``, zero off the band. Hoisted out of the transverse loops, where it is constant. Parameters ---------- omega : numpy.ndarray Absolute angular frequency, rad/s. zmask : float Mask-plane distance from the focus, m. achromatic_wavelength : float or None, optional Map every positive frequency as this wavelength, m (an achromatic window); None for the physical, frequency-dependent mapping. Returns ------- numpy.ndarray The factor in m/(rad/m); zero at non-positive frequencies, where the mapping diverges. """ if achromatic_wavelength is not None: omega = np.where(omega > 0.0, 2 * np.pi * c / achromatic_wavelength, omega) return np.where(omega > 0.0, zmask * c / np.where(omega > 0.0, omega, 1.0), 0.0)
[docs] def check_windows_share_a_mask(windows: Sequence[WindowSpec]) -> None: """Require one physical mask, which the fused reduction assumes. Parameters ---------- windows : sequence of WindowSpec The collection apertures, with resolved edge parameters. Raises ------ ReductionError If the windows differ in anything but their diameter, or an edge parameter is unresolved. """ keys = { ( w.holex, w.holey, w.zmask, w.apod, w.apod_param, w.weighting, w.achromatic_wavelength, ) for w in windows } if len(keys) != 1: raise ReductionError( "the reduction covers every collection window in one pass over the " "state, sharing the mask-plane radius, so the windows must differ only " f"in diameter; got {len(keys)} distinct (centre, distance, profile, " "weighting) combinations" ) if windows[0].apod_param is None: raise ReductionError("WindowSpec.apod_param must be resolved before extraction")
[docs] def assemble_observation( # noqa: PLR0913 - the slots, their scales and the rate tables reduced: Float[np.ndarray, "n_slots n_omega"], n_windows: int, cells: int, energy_prefactor: float, edge_fraction: float, *, gamma_omega: Float[np.ndarray, " n_omega"], gamma_lap: Float[np.ndarray, " n_omega"], gd_band: Float[np.ndarray, " n_omega"], ) -> Observation: """Turn one reduction's slots into the driver's observation. Parameters ---------- reduced : numpy.ndarray The reduced slots, shape ``(n_slots(n_windows), nt)``. n_windows : int Collection windows the reduction covered. cells : int Transverse samples ``n * n``, the divisor turning the signed sum into the on-axis mean. energy_prefactor : float Converts summed ``eta |E|^2`` to joules. edge_fraction : float The time-window edge diagnostic, which needs a transform and so is computed by the caller (NaN when not requested). gamma_omega, gamma_lap : numpy.ndarray The spectral absorber's amplitude rate and the lap budget's share of it, ``(nt,)``, 1/m. gd_band : numpy.ndarray The lap budget's 0/1 indicator, ``(nt,)``. Returns ------- Observation The per-window traces, the full-plane spectrum and the scalar diagnostics of this reduction. """ nt = reduced.shape[1] i_win = np.empty((n_windows, nt)) i_reimaged = np.empty((n_windows, nt)) for iw in range(n_windows): slot = N_SHARED_SLOTS + SLOTS_PER_WINDOW * iw i_win[iw] = reduced[slot] # The centre pixel of the 2-D inverse transform is the alternating-signed # mean, so the on-axis spectrum needs no transform: the mean amplitude # paired with the mean of its closure, Re(A conj(G)). i_reimaged[iw] = ( reduced[slot + 1] * reduced[slot + 3] + reduced[slot + 2] * reduced[slot + 4] ) / (cells * cells) beam = reduced[SLOT_POWER] power = float(beam.sum()) return Observation( i_omega_win=i_win, i_omega_reimaged=i_reimaged, i_omega_full=reduced[SLOT_REGION].copy(), i_omega_beam=beam.copy(), energy=energy_prefactor * power, absorb_omega=float(np.sum((gamma_omega - gamma_lap) * beam)), absorb_lap=float(np.sum(gamma_lap * beam)), absorb_k=float(reduced[SLOT_ABSORB_K].sum()), gd_band_power=float(np.sum(gd_band * beam)) / power, alias_fraction=1.0 - float(reduced[SLOT_INNER].sum()) / power, edge_fraction=edge_fraction, )