# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""The fused host reduction of a saved plane to the measured spectra and diagnostics.
solprop hands back each saved plane as a read-only host array (:mod:`pnps.bridge`);
this module reduces it, immediately, to an :class:`~pnps.observables.Observation` in
**one** traversal of the state:
- all the accumulators of :mod:`pnps.observables` -- per window the collected energy
and the on-axis sum with its magnetic closure, plus the energy, the signal region,
the two absorber channels and the group-delay band -- are filled together, each
weighted by the medium's axial admittance (:mod:`pnps.flux`), with the admittance
and the mask-plane radius computed once per element and shared across the windows;
- the two-stage form (a partial per transverse row, then a reduction over rows in
index order) makes the result **deterministic and thread-count invariant**.
The optional time-window edge diagnostic needs an inverse transform along the
frequency axis. It is computed over blocks of transverse rows with
:func:`scipy.fft.ifft`, so it needs a block-sized scratch array rather than a second
field (``Config.edge_diagnostic``; off by default, when it is reported as NaN).
The numerical reference for everything here is
:func:`pnps.extraction.extract_observables` with
:func:`pnps.reference.linear_diagnostics` and :func:`pnps.reference.time_edge_fraction`.
"""
import math
from collections.abc import Sequence
from typing import no_type_check
import numpy as np
import scipy.fft
from jaxtyping import Bool, Complex, Float
from numba import get_num_threads, njit, prange
from pnps.beams import quadrature_holediam
from pnps.exceptions import ReductionError
from pnps.extraction import WindowSpec
from pnps.geometry import SignalRegion
from pnps.kernels import admittance, apod_code, mask_plane_radius, profile_weight
from pnps.observables import (
N_SHARED_SLOTS,
SLOT_ABSORB_K,
SLOT_INNER,
SLOT_POWER,
SLOT_REGION,
SLOTS_PER_WINDOW,
Observation,
assemble_observation,
check_windows_share_a_mask,
inner_half_width,
mapping_factor,
n_slots,
)
from pnps.reference import OperatorTables
__all__ = ["EDGE_FRACTION", "Reducer"]
#: Fraction of the time window counted as "edge" by the edge diagnostic, split
#: between the two ends (inherited convention).
EDGE_FRACTION = 0.05
#: Target size of one block of the blocked edge-diagnostic transform, in bytes.
_EDGE_BLOCK_BYTES = 64 << 20
# --- Kernels -----------------------------------------------------------
#
# Every kernel is `prange` over the slow transverse axis with the inner loop along
# omega, which is contiguous in the (ky, kx, omega) layout. Each iteration touches
# only its own row, so there are no races and no reduction: the parallelism is
# exact, not merely deterministic.
@njit(parallel=True, cache=True)
@no_type_check
def _stage_a( # noqa: PLR0913, PLR0917 - a numba kernel takes its buffers positionally
e: Complex[np.ndarray, "n_y n_x n_omega"],
kx: Float[np.ndarray, " n_x"],
omega: Float[np.ndarray, " n_omega"],
factor: Float[np.ndarray, " n_omega"],
positive: Bool[np.ndarray, " n_omega"],
k2: Complex[np.ndarray, " n_omega"],
kperp2: Float[np.ndarray, "n_y n_x"],
gamma_k: Float[np.ndarray, "n_y n_x"],
active: Bool[np.ndarray, " n_omega"],
holex: float,
holey: float,
diams: Float[np.ndarray, " n_windows"],
apod_code: int,
apod_param: float,
quadrature: bool,
region_kx: Float[np.ndarray, " n_omega"],
region_ky: Float[np.ndarray, " n_omega"],
region_k2: Float[np.ndarray, " n_omega"],
inner_half: float,
partial: Float[np.ndarray, "n_y n_slots n_omega"],
) -> None:
"""Fill every accumulator for one transverse row of the state.
The admittance and the chromatic radius are computed **once per element** and
reused by all the windows -- they are holes in one mask, so they share a centre
and a mask distance, and only the diameter differs. Windows whose profile is
exactly zero at this radius (the raised cosine has compact support) cost nothing
beyond that test.
Parameters
----------
e : numpy.ndarray
Spectral state ``(n_y, n_x, n_omega)``, complex128, V/m (unnormalised DFT).
kx : numpy.ndarray
Momentum axis shared by x and y, ``(n_x,)``, rad/m.
omega : numpy.ndarray
Absolute angular frequency, FFT-ordered, ``(n_omega,)``, rad/s.
factor : numpy.ndarray
Angle-to-position mapping ``zmask c / omega``, ``(n_omega,)``, m/(rad/m);
zero at non-positive frequencies.
positive : numpy.ndarray
Boolean mask of the bins with ``omega > 0``, ``(n_omega,)``; only these
enter the window accumulators.
k2 : numpy.ndarray
The material wavenumber squared, ``(n_omega,)``, complex, rad^2/m^2.
kperp2 : numpy.ndarray
``kx^2 + ky^2`` indexed ``[iy, ix]``, ``(n_y, n_x)``, rad^2/m^2.
gamma_k : numpy.ndarray
Transverse-wavevector ramp amplitude rate, ``(n_y, n_x)``, 1/m.
active : numpy.ndarray
Boolean hard band limit, ``(n_omega,)``; all true when there is none. The
admittance is zero off it.
holex, holey : float
Hole centre in the mask plane, m.
diams : numpy.ndarray
Effective hole diameter of each window, ``(n_windows,)``, m.
apod_code : int
Edge-profile code (:func:`pnps.kernels.apod_code`) shared by the windows.
apod_param : float
Supergaussian order, or the tanh/raised-cosine width in m.
quadrature : bool
Whether the windows weight power by the profile (quadrature weighting)
rather than by its square (an amplitude filter).
region_kx, region_ky : numpy.ndarray
Exclusive upper bounds of the signal region on ``kx`` and ``ky``,
``(n_omega,)``, rad/m (:class:`pnps.geometry.SignalRegion`).
region_k2 : numpy.ndarray
Its exclusive upper bound on ``kx^2 + ky^2``, ``(n_omega,)``, rad^2/m^2.
inner_half : float
The inner box's half-width, rad/m: a column is inside when
``-inner_half < k <= inner_half`` on both axes, solprop's half-open box
``[-h, h)`` on the physical wavevector ``-k``
(:func:`pnps.statistics.inner_box_region`).
partial : numpy.ndarray
Output: the per-row accumulators ``(n_y, n_slots, n_omega)``, overwritten,
with ``n_slots`` from :func:`pnps.observables.n_slots`.
"""
ny, nx, nt = e.shape
n_win = diams.shape[0]
for iy in prange(ny):
part = partial[iy]
part[:, :] = 0.0
ky = kx[iy]
inner_row = -inner_half < ky <= inner_half
for ix in range(nx):
kp2 = kperp2[iy, ix]
gk = gamma_k[iy, ix]
sign = 1.0 if ((iy + ix) & 1) == 0 else -1.0
kxx = kx[ix]
inner = inner_row and -inner_half < kxx <= inner_half
for k in range(nt):
z = e[iy, ix, k]
y = admittance(k2[k], kp2, omega[k]) if active[k] else 0.0j
y_re, y_im = y.real, y.imag
power = y_re * (z.real * z.real + z.imag * z.imag)
# The element's magnetic closure, conj(y) z.
g_re = y_re * z.real + y_im * z.imag
g_im = y_re * z.imag - y_im * z.real
part[SLOT_POWER, k] += power
if kxx < region_kx[k] and ky < region_ky[k] and kp2 < region_k2[k]:
part[SLOT_REGION, k] += power
part[SLOT_ABSORB_K, k] += gk * power
if inner:
part[SLOT_INNER, k] += power
if not positive[k]:
continue
radius = mask_plane_radius(kx[ix], kx[iy], factor[k], holex, holey)
for iw in range(n_win):
weight = profile_weight(radius, diams[iw], apod_code, apod_param)
if weight == 0.0:
continue
slot = N_SHARED_SLOTS + SLOTS_PER_WINDOW * iw
if quadrature:
part[slot, k] += weight * power
else:
part[slot, k] += weight * weight * power
part[slot + 1, k] += sign * (weight * z.real)
part[slot + 2, k] += sign * (weight * z.imag)
part[slot + 3, k] += sign * (weight * g_re)
part[slot + 4, k] += sign * (weight * g_im)
@njit(parallel=True, cache=True)
@no_type_check
def _stage_b(
partial: Float[np.ndarray, "n_rows n_slots n_omega"],
out: Float[np.ndarray, "n_slots n_omega"],
) -> None:
"""Reduce the per-row partials over rows, in index order.
Parallel over accumulators rather than over rows, so every sum runs over ``iy``
ascending however many threads there are: the result is bitwise repeatable and
thread-count invariant.
Parameters
----------
partial : numpy.ndarray
The per-row accumulators ``(n_y, n_slots, n_omega)`` from :func:`_stage_a`.
out : numpy.ndarray
Output: the reduced accumulators ``(n_slots, n_omega)``, overwritten.
"""
n_rows, n_slot, nt = partial.shape
for slot in prange(n_slot):
for k in range(nt):
total = 0.0
for iy in range(n_rows):
total += partial[iy, slot, k]
out[slot, k] = total
@njit(parallel=True, cache=True)
@no_type_check
def _time_power(
a: Complex[np.ndarray, "n_rows n_x n_t"], partial: Float[np.ndarray, "n_rows n_t"]
) -> None:
"""Per-row power spectrum along the time axis of a transformed block of rows.
Parameters
----------
a : numpy.ndarray
A block of rows transformed to time, ``(n_block, n_x, n_t)``, complex.
partial : numpy.ndarray
Output: ``sum over x of |a|^2`` per row, ``(n_block, n_t)``, overwritten;
in the square of the unit of ``a``.
"""
ny, nx, nt = a.shape
for iy in prange(ny):
row = partial[iy]
for k in range(nt):
row[k] = 0.0
for ix in range(nx):
for k in range(nt):
z = a[iy, ix, k]
row[k] += z.real * z.real + z.imag * z.imag
# --- The reducer -------------------------------------------------------
[docs]
class Reducer:
"""Reduce saved planes of one configuration on the host.
Holds the operator and window tables and the small reduction workspace (the
per-row partials, ``n * n_slots * nt`` doubles); nothing field-sized.
Parameters
----------
tables : OperatorTables
The operator the diagnostics describe (the bridge's configured one, see
:func:`pnps.bridge.bridge_tables`).
kx : numpy.ndarray
The momentum axis shared by x and y, rad/m.
windows : sequence of WindowSpec
Collection apertures with resolved edge parameters, differing only in
diameter.
energy_prefactor : float
Converts summed ``eta |E|^2`` to joules (:func:`pnps.pulse.energy_prefactor`).
edge_diagnostic : bool
Whether to compute the time-window edge fraction (one blocked inverse
transform along omega per plane); NaN is reported otherwise.
region : SignalRegion
The momentum region ``i_omega_full`` sums
(:attr:`pnps.setup.Setup.signal_region`).
Raises
------
ReductionError
If the windows do not share a centre, mask distance, edge profile and
weighting.
"""
def __init__(
self,
tables: OperatorTables,
kx: Float[np.ndarray, " n_x"],
windows: Sequence[WindowSpec],
energy_prefactor: float,
edge_diagnostic: bool,
region: SignalRegion,
) -> None:
check_windows_share_a_mask(windows)
window = windows[0]
self._n, self._nt = len(kx), len(tables.omega)
self._kx = np.ascontiguousarray(kx, dtype=float)
self._omega = np.ascontiguousarray(tables.omega, dtype=float)
self._positive = self._omega > 0.0
self._k2 = np.ascontiguousarray(tables.k2, dtype=complex)
self._kperp2 = np.ascontiguousarray(tables.kperp2, dtype=float)
self._gamma_omega = np.ascontiguousarray(tables.gamma_omega, dtype=float)
self._gamma_lap = np.ascontiguousarray(tables.gamma_lap, dtype=float)
self._gamma_k = (
np.zeros((self._n, self._n))
if tables.gamma_k is None
else np.ascontiguousarray(tables.gamma_k, dtype=float)
)
self._gd_band = np.ascontiguousarray(tables.gd_band, dtype=float)
self._active = (
np.ones(self._nt, dtype=np.bool_)
if tables.active is None
else np.ascontiguousarray(tables.active, dtype=np.bool_)
)
self._quadrature = window.weighting == "quadrature"
self._window_code = apod_code(window.apod)
self._window_param = float(window.apod_param or 0.0)
self._holex, self._holey = float(window.holex), float(window.holey)
# A quadrature weight is shrunk by its own second moment so that it encloses
# exactly the nominal hole area; an amplitude filter is the physical mask
# and is used at its nominal diameter.
self._diams = np.array(
[
quadrature_holediam(w.holediam, w.apod, self._window_param)
if self._quadrature
else w.holediam
for w in windows
],
dtype=float,
)
self._window_factor = mapping_factor(
self._omega, float(window.zmask), window.achromatic_wavelength
)
self._region_kx = np.ascontiguousarray(region.kx_max, dtype=float)
self._region_ky = np.ascontiguousarray(region.ky_max, dtype=float)
self._region_k2 = np.ascontiguousarray(region.kperp2_max, dtype=float)
self._inner_half = inner_half_width(self._kx)
self._n_windows = len(windows)
self._energy_prefactor = float(energy_prefactor)
self._edge_diagnostic = bool(edge_diagnostic)
self._n_edge = max(1, int(self._nt * EDGE_FRACTION / 2))
self._partial = np.zeros((self._n, n_slots(self._n_windows), self._nt))
self._reduced = np.zeros((n_slots(self._n_windows), self._nt))
[docs]
def reduce(self, field: Complex[np.ndarray, "n_y n_x n_omega"]) -> Observation:
"""Reduce one saved plane to the spectra and the diagnostics.
Parameters
----------
field : numpy.ndarray
The state ``(n, n, nt)``, complex128, C-contiguous; only read, so a
read-only view of a backend's live state is fine (reduce it before the
backend steps again).
Returns
-------
Observation
The windowed and full spectra, the energy and the diagnostics of the
plane.
Raises
------
ReductionError
If the field has the wrong shape.
"""
expected = (self._n, self._n, self._nt)
if field.shape != expected:
raise ReductionError(f"field has shape {field.shape}, expected {expected}")
_stage_a(
field, self._kx, self._omega, self._window_factor, self._positive,
self._k2, self._kperp2, self._gamma_k, self._active,
self._holex, self._holey, self._diams, self._window_code,
self._window_param, self._quadrature, self._region_kx, self._region_ky,
self._region_k2, self._inner_half, self._partial,
) # fmt: skip
_stage_b(self._partial, self._reduced)
edge = self.edge_fraction(field) if self._edge_diagnostic else math.nan
return assemble_observation(
self._reduced,
self._n_windows,
self._n * self._n,
self._energy_prefactor,
edge,
gamma_omega=self._gamma_omega,
gamma_lap=self._gamma_lap,
gd_band=self._gd_band,
)
[docs]
@property
def edge_diagnostic(self) -> bool:
"""Whether the time-window edge fraction is computed (NaN otherwise).
Returns
-------
bool
True when :meth:`reduce` computes the edge fraction.
"""
return self._edge_diagnostic
[docs]
def edge_fraction(self, field: Complex[np.ndarray, "n_y n_x n_omega"]) -> float:
"""Return the field-norm fraction in the outer edges of the time window.
A blocked inverse transform along omega, so the scratch is one block of rows
rather than a field. The ratio is invariant under the transform's
normalisation, and the blocks are summed in row order, so the result does not
depend on the block size beyond rounding. It is the one per-plane observable
solprop's statistics cannot form (it is a time-domain quantity), so a
field-free run (``Config.reduction = "solprop"``) still observes the field
when it is asked for.
Parameters
----------
field : numpy.ndarray
The state ``(n, n, nt)``.
Returns
-------
float
The fraction of :data:`EDGE_FRACTION` of the window, split between its ends.
"""
row_bytes = 16 * self._n * self._nt
block = max(1, min(self._n, _EDGE_BLOCK_BYTES // row_bytes))
p_t = np.zeros(self._nt)
rows = np.zeros((block, self._nt))
# The same width as the numba pool, which the engine's thread settings
# already size for this process (never the host's core count).
workers = get_num_threads()
for start in range(0, self._n, block):
stop = min(self._n, start + block)
transformed = np.asarray(
scipy.fft.ifft(field[start:stop], axis=-1, workers=workers)
)
_time_power(transformed, rows[: stop - start])
p_t += rows[: stop - start].sum(axis=0)
edge = p_t[: self._n_edge].sum() + p_t[-self._n_edge :].sum()
return float(edge / p_t.sum())