Source code for pnps.statistics

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

"""Form this package's per-plane observables from solprop's far-field statistics.

With ``Config.reduction = "solprop"`` a delay point keeps no field: solprop evaluates
its own statistics at every save plane (SEP 23's far-field statistics, on SEP 22's
statistics-only planes) and this module turns them back into this package's
:class:`~pnps.observables.Observation`, in this package's units. The host reduction
(:mod:`pnps.reduce_numba`) is the reference it is tested against.

Notes
-----
*The mapping.* Each observable comes from one solprop statistic, scaled:

=====================  ========================================  ==================
observable             solprop statistic                         scale
=====================  ========================================  ==================
``i_omega_win``        ``aperture_spectrum`` (the windows as an  ``1/U_S``
                       :class:`solprop.stats.ApertureSet`)
``i_omega_reimaged``   ``aperture_on_axis_spectrum``             ``1/U_A``
``i_omega_full``       TG: ``region_spectrum``, one box: the     ``1/U_S``
                       signal quadrant. SD: the last row of
                       ``aperture_spectrum``, a hard half-plane
                       of the mask beyond the gate-side edge
``i_omega_beam``       ``beam_spectrum``                         ``1/U_S``
``energy``             ``energy``                                1
``absorb_omega``       ``absorbed_power[0]`` (spectral channel:  ``1/(2 U_P)``
                       the band edges)
``absorb_lap``         ``absorbed_power[4]`` (custom channel:    ``1/(2 U_P)``
                       the lap budget)
``gd_band_power``      ``beam_spectrum``, the lap-budget bins    ratio
                       over all
``alias_fraction``     ``region_spectrum``, the inner box's      ratio
                       row, against ``beam_spectrum``
``absorb_k``           ``absorbed_power[1]`` (transverse         ``1/(2 U_P)``
                       channel)
``edge_fraction``      none: a time-domain quantity; stays on    --
                       the host
=====================  ========================================  ==================

*Measure.* Both codes measure energy by the medium's axial flux (solprop's SEP 34,
:mod:`pnps.flux`): every statistic weights ``|E|^2`` by the admittance ``eta``, as
the host reduction does, so the constants below are the vacuum ones and ``eta`` is
already inside both sides.

*Units.* The state is the unnormalised 3-D DFT of the field in V/m in both codes (they
share the raw-DFT convention, ``docs/dev/numerics.md``), so solprop reads this package's
state as its own and its statistics are physical: on an envelope grid of ``n_t`` samples
at ``dt``, and ``N = n^2`` columns of spacing ``dx``, solprop's spectral weight is
``w = dx^2 / N`` and its spectral density ``(dt^2 / 2 pi) |E|^2``. Hence

- ``U_S = (eps_0 c / 2) (dx^2 / N) (dt^2 / 2 pi)``, J/(rad/s) per unit of
  ``sum_c eta |E|^2``: a spectrum summed over columns;
- ``U_A = (eps_0 c / 2) (dt^2 / 2 pi)``, J s/m^2 per unit of ``Re(A conj(G))``: the
  on-axis spectrum, whose amplitude ``A = sum_c alpha_c W E`` and closure ``G`` (the
  same sum of ``conj(y) E``) already carry the ``1/N`` of the on-axis weight
  ``alpha_c = (-1)^(ix+iy) / N``;
- ``U_P = (eps_0 c / 2) (dx^2 / N) (dt / n_t)``, J/m per unit of ``sum r eta |E|^2``:
  the absorbed powers, with solprop's power rates ``r = 2 x`` this package's
  amplitude rates.

``energy`` needs no constant: ``(eps_0 c / 2) (dx^2 / N) (dt / n_t) sum eta |E|^2``
is exactly :func:`pnps.pulse.energy_prefactor` times ``sum eta |E|^2``.

*Sign convention.* SEP 23's aperture centres are physical mask-plane positions, and a
stored column at transverse wavevector ``k`` travels along ``-k`` (SEP 23, equation
(1)). This package's window centres are in the stored axes (the signal corner is at
``(-d, -d)`` with the beamlets launched at the stored ``+k`` corners), so the centres
are negated: ``X = -holex``. The signal quadrant is the stored ``kx, ky < 0`` corner,
upper half of each FFT-ordered axis including the Nyquist column, hence the physical box
``[dk/2, inf) x [dk/2, inf)``: its lower edge lies between the zero column and the first
positive one, so it selects exactly the stored columns ``n/2 .. n-1``.
"""

import math
import warnings
from collections.abc import Mapping, Sequence
from dataclasses import dataclass

import numpy as np
from jaxtyping import Float, Shaped
from solprop.constants import EPS0, C
from solprop.exceptions import SolpropError, SolpropWarning
from solprop.stats import ApertureSet, StatsSpec

from pnps.exceptions import ReductionError
from pnps.extraction import WindowSpec
from pnps.observables import Observation, inner_half_width

__all__ = [
    "STATISTICS",
    "StatisticsScale",
    "aperture_set",
    "inner_box_region",
    "observation_from_statistics",
    "signal_quadrant_region",
    "statistics_refusal",
    "statistics_spec",
    "statistics_unavailable",
]

#: The solprop statistics a field-free delay point asks for at every plane.
STATISTICS = (
    "energy",
    "beam_spectrum",
    "aperture_spectrum",
    "aperture_on_axis_spectrum",
    "region_spectrum",
    "absorbed_power",
)

#: Indices of the channels of solprop's ``absorbed_power`` this package reports
#: (SEP 23 section 4.9): the band edges (solprop's collar, here this package's edge
#: ramps), the transverse ramp, and the custom rate, which is the lap budget.
_SPECTRAL_CHANNEL = 0
_TRANSVERSE_CHANNEL = 1
_CUSTOM_CHANNEL = 4

#: The window profiles solprop's apertures can express (SEP 23 section 4.4).
_SOLPROP_PROFILES = ("hard", "tanh", "rcos", "supergauss")


[docs] def statistics_refusal( windows: Sequence[WindowSpec], *, exact: bool = False ) -> str | None: """Return why the windows cannot be solprop apertures, or None if they can. solprop's :class:`~solprop.stats.ApertureSet` shares one profile and one weighting across the set and has the four radial profiles; this package's pixel-area rendering (``"area"``) is an input-hole rendering with no aperture equivalent. The edge-width limits are solprop's own and are checked when the set is built. As exact hard discs every window is a physical hole whatever its rendering, so only an achromatic window is refused. Parameters ---------- windows : sequence of WindowSpec The collection windows, with resolved edge parameters. exact : bool, optional Ask for the windows as exact hard discs (``Config.exact_windows``). Returns ------- str or None The reason, or None. """ if any(w.achromatic_wavelength is not None for w in windows): return "solprop's apertures are physical mask holes; the windows are achromatic" if exact: return None profiles = {w.apod for w in windows} weightings = {w.weighting for w in windows} if len(profiles) != 1 or len(weightings) != 1: return ( "solprop's apertures share one profile and one weighting; the windows " f"have profiles {sorted(profiles)} and weightings {sorted(weightings)}" ) (profile,) = profiles if profile not in _SOLPROP_PROFILES: return ( f"solprop's apertures have the profiles {_SOLPROP_PROFILES}; the windows " f"use {profile!r}" ) if any(w.apod_param is None for w in windows): return "the windows' edge parameters must be resolved first" return None
[docs] def aperture_set( windows: Sequence[WindowSpec], signal: tuple[float, float] | None = None, *, exact: bool = False, ) -> ApertureSet: """Return the windows as a solprop aperture set. The centres are negated into SEP 23's physical axes (see the module notes). The diameters are the nominal ones under both weightings: solprop applies the quadrature correction of :func:`pnps.beams.quadrature_holediam` itself (its equation (6), with the same second moments). With `exact`, each window is its hard disc integrated exactly (solprop's ``exact`` profile, SEP 53) over the nonlinear part of the field, the state less the input carried by the linear flow, as :class:`pnps.exact_windows.ExactWindows` integrates it on the host. The rendering (``apod``, ``weighting``) then plays no part. The whole set reduces that part, so the SD signal half-plane does too: no linear light reaches it behind compact input holes, so there it is the field. Parameters ---------- windows : sequence of WindowSpec The collection windows, with resolved edge parameters. signal : tuple of float or None, optional The SD signal region as a mask-plane edge and its distance, m (:func:`pnps.geometry.signal_half_plane`), appended as a hard ``half_plane_x_ge`` row; None for none. exact : bool, optional The windows as exact hard discs on the nonlinear field (``Config.exact_windows``). Returns ------- solprop.stats.ApertureSet One aperture per window, labelled by the trace names, and the signal half-plane last when there is one. Raises ------ ReductionError If the windows cannot be expressed (:func:`statistics_refusal`), or solprop refuses the set (an edge too wide for its hole, say), naming the reason. """ reason = statistics_refusal(windows, exact=exact) if reason is not None: raise ReductionError(f"{reason}; use Config.reduction = 'host'") profile = "exact" if exact else windows[0].apod edgeless = profile in ("hard", "exact") edges = [0.0 if edgeless else float(w.apod_param or 0.0) for w in windows] # An exact disc is the hard hole itself, collected under amplitude weighting. weighting = "amplitude" if exact else windows[0].weighting field = "nonlinear" if exact else "total" rows = { "centres": [[-w.holex, -w.holey] for w in windows], "diameters": [w.holediam for w in windows], "distances": [w.zmask for w in windows], "labels": tuple(f"window {j + 1}" for j in range(len(windows))), } try: if signal is None: return ApertureSet( edges=None if edgeless else edges, profile=profile, # type: ignore[arg-type] # checked by statistics_refusal weighting=weighting, field=field, **rows, ) edge, distance = signal return ApertureSet( centres=[*rows["centres"], [edge, 0.0]], diameters=[*rows["diameters"], 0.0], distances=[*rows["distances"], distance], edges=None if edgeless else [*edges, 0.0], shapes=(*("circle" for _ in windows), "half_plane_x_ge"), profiles=(*(profile for _ in windows), "hard"), # type: ignore[arg-type] weighting=weighting, labels=(*rows["labels"], "signal"), field=field, ) except SolpropError as error: # a refused set (ProcessingError since solprop 0.3) raise ReductionError( f"solprop refuses the windows as apertures ({error}); use " "Config.reduction = 'host'" ) from error
[docs] def signal_quadrant_region(kx: Float[np.ndarray, " n_x"]) -> Float[np.ndarray, "1 4"]: """Return the signal quadrant as one row of solprop's ``spectral_regions``. Parameters ---------- kx : numpy.ndarray The stored momentum axis shared by x and y, FFT-ordered, rad/m. Returns ------- numpy.ndarray ``[[dk/2, inf, dk/2, inf]]`` in physical rad/m, which selects exactly the stored columns ``n/2 .. n-1`` of each axis. """ half_step = 0.5 * float(kx[1] - kx[0]) return np.array([[half_step, math.inf, half_step, math.inf]])
[docs] def inner_box_region(kx: Float[np.ndarray, " n_x"]) -> Float[np.ndarray, "1 4"]: """Return the aliasing reading's inner box as one row of ``spectral_regions``. Parameters ---------- kx : numpy.ndarray The stored momentum axis shared by x and y, rad/m. Returns ------- numpy.ndarray ``[[-h, h, -h, h]]`` with ``h`` from :func:`pnps.observables.inner_half_width`; symmetric, so the same in the physical axes. """ half = inner_half_width(kx) return np.array([[-half, half, -half, half]])
[docs] def statistics_spec( windows: Sequence[WindowSpec], kx: Float[np.ndarray, " n_x"], signal: tuple[float, float] | None = None, *, exact: bool = False, ) -> StatsSpec: """Return the statistics a field-free delay point asks solprop for. Parameters ---------- windows : sequence of WindowSpec The collection windows, with resolved edge parameters. kx : numpy.ndarray The stored momentum axis, rad/m. signal : tuple of float or None, optional The SD signal half-plane (:func:`pnps.geometry.signal_half_plane`), or None for the TG quadrant. exact : bool, optional The windows as exact hard discs on the nonlinear field (:func:`aperture_set`). Returns ------- solprop.stats.StatsSpec :data:`STATISTICS`, with the apertures and the regions: for TG the signal quadrant, and for both the aliasing reading's inner box (:func:`inner_box_region`), last. Raises ------ ReductionError If the windows cannot be solprop apertures. """ regions = ( inner_box_region(kx) if signal is not None else np.vstack([signal_quadrant_region(kx), inner_box_region(kx)]) ) return StatsSpec( names=STATISTICS, apertures=aperture_set(windows, signal, exact=exact), spectral_regions=regions, )
[docs] def statistics_unavailable( windows: Sequence[WindowSpec], kx: Float[np.ndarray, " n_x"], signal: tuple[float, float] | None = None, *, exact: bool = False, ) -> str | None: """Return why solprop should not reduce these windows, or None if it should. The choice behind ``reduction="auto"``: solprop's statistics are used only when solprop accepts the windows as apertures (:func:`statistics_refusal` and solprop's own edge-width limits) *and* raises no warning about them. A warning (for example a tanh edge that slopes at the hole centre, collected with a lattice error near 1e-5) is an accuracy caveat the host reduction does not have, so it is a reason to stay on the host. Parameters ---------- windows : sequence of WindowSpec The collection windows, with resolved edge parameters. kx : numpy.ndarray The stored momentum axis, rad/m. signal : tuple of float or None, optional The SD signal half-plane, or None for the TG quadrant. exact : bool, optional The windows as exact hard discs on the nonlinear field (:func:`aperture_set`). Returns ------- str or None The reason, or None when solprop's statistics are to be used. """ reason = statistics_refusal(windows, exact=exact) if reason is not None: return reason with warnings.catch_warnings(): warnings.simplefilter("error", SolpropWarning) try: statistics_spec(windows, kx, signal, exact=exact) except (ReductionError, SolpropWarning) as error: return str(error) return None
[docs] @dataclass(frozen=True) class StatisticsScale: """The constants that turn solprop's physical statistics into this package's units. Attributes ---------- spectrum : float ``U_S``, J/(rad/s) per unit of ``sum_c |E|^2`` (module notes). on_axis : float ``U_A``, J s/m^2 per unit of ``|A|^2``. power : float ``U_P``, J/m per unit of ``sum r |E|^2``. """ spectrum: float on_axis: float power: float
[docs] @classmethod def for_grids( cls, dt: float, n_t: int, spectral_weight: float ) -> "StatisticsScale": # noqa: UP037 - bound after the class body """Form the constants from the grids solprop evaluates on. Parameters ---------- dt : float Time step of the envelope grid, s. n_t : int Temporal samples. spectral_weight : float The solprop transverse spectral weight of one column, ``dx^2 / N`` in m^2 (``FreeGrid.spectral_weights``, the same for every column). Returns ------- StatisticsScale The unit constants ``U_S``, ``U_A`` and ``U_P`` for those grids. Examples -------- >>> scale = StatisticsScale.for_grids(1e-16, 64, 1e-12 / 16) >>> round(scale.spectrum / scale.on_axis * 16 / 1e-12, 12) 1.0 """ half = 0.5 * EPS0 * C density = dt * dt / (2 * math.pi) return cls( spectrum=half * spectral_weight * density, on_axis=half * density, power=half * spectral_weight * dt / n_t, )
[docs] def observation_from_statistics( values: Mapping[str, Shaped[np.ndarray, "*_"]], scale: StatisticsScale, gd_band: Float[np.ndarray, " n_omega"], edge_fraction: float, *, signal_row: bool = False, ) -> Observation: """Turn one plane's solprop statistics into this package's observation. Parameters ---------- values : mapping The solprop statistics at one plane (:data:`STATISTICS`), without the batch axis. scale : StatisticsScale The unit constants. gd_band : numpy.ndarray The lap-budget indicator, ``(nt,)``. edge_fraction : float The time-window edge diagnostic, computed on the host (NaN when off). signal_row : bool, optional Whether the signal region is the aperture set's last row (SD), rather than ``region_spectrum`` (TG). Returns ------- Observation The plane's spectra and diagnostics in this package's units. """ beam = np.asarray(values["beam_spectrum"], dtype=float) absorbed = np.asarray(values["absorbed_power"], dtype=float) apertures = np.asarray(values["aperture_spectrum"], dtype=float) / scale.spectrum on_axis = np.asarray(values["aperture_on_axis_spectrum"], dtype=float) regions = np.asarray(values["region_spectrum"], dtype=float) / scale.spectrum if signal_row: apertures, full, on_axis = apertures[:-1], apertures[-1], on_axis[:-1] else: full = regions[0] return Observation( i_omega_win=apertures, i_omega_reimaged=on_axis / scale.on_axis, i_omega_full=full, i_omega_beam=beam / scale.spectrum, energy=float(np.asarray(values["energy"]).reshape(())), absorb_omega=float(absorbed[_SPECTRAL_CHANNEL]) / (2 * scale.power), absorb_lap=float(absorbed[_CUSTOM_CHANNEL]) / (2 * scale.power), absorb_k=float(absorbed[_TRANSVERSE_CHANNEL]) / (2 * scale.power), gd_band_power=float(np.sum(gd_band * beam) / np.sum(beam)), alias_fraction=1.0 - float(np.sum(regions[-1])) / float(np.sum(beam / scale.spectrum)), edge_fraction=edge_fraction, )