# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Reduction of the propagated state to the measured spectra.
The propagation state already lives in ``(ky, kx, omega)``, so extracting a
spectrum needs no temporal FFT — only reductions over the transverse-momentum
axes. Per collection window three observables are produced:
- ``i_omega_win``: the spectrum a spectrometer collecting *all* the windowed
light would record, ``sum_k |W E|^2``;
- ``i_omega_reimaged``: the on-axis re-imaged spectrum — the centre pixel of
the 2-D inverse FFT of the windowed field, computed without any FFT via the
exact identity (even grids) that the centre pixel equals the
``(-1)^(iy+ix)``-weighted mean;
- ``i_omega_full``: the un-windowed spectrum of the signal region
(:func:`pnps.geometry.signal_region`: in the TG boxcar the quadrant ``kx < 0,
ky < 0``, the second half of each FFT-ordered axis), so
``i_omega_win / i_omega_full`` is the exact per-frequency collection
efficiency.
The collection windows use the same chromatic hole model as the input masks.
A run evaluates them on the fly inside the fused host reduction
(:mod:`pnps.reduce_numba`), so no window array is ever materialised;
:func:`extract_observables` here is the plain NumPy statement of the same
reductions, the reference that pass is tested against.
A window profile can enter in either of two ways, selected by
``WindowSpec.weighting``. As an *amplitude filter* it models a hole whose
transmission really is graded, and the collected energy carries the profile
squared. As a *quadrature weight*, the default, the same profile is instead a
rule for integrating over a genuinely hard hole, which is what the instrument
actually has: one weight then serves both observables and reproduces the nominal
aperture, at the cost of a small sampling ripple where the hole spans few k
pixels. See :class:`WindowSpec`.
Note the spectra inherit the unnormalised-FFT units of the state: at fixed
physical grid extent they scale as the fourth power of the transverse sample
count (``i_omega_reimaged``, a real-space sample, is grid-invariant).
"""
from dataclasses import dataclass
from typing import Literal
import numpy as np
from jaxtyping import Complex, Float
from scipy.constants import c
from pnps.beams import chromatic_mask, quadrature_holediam
from pnps.exceptions import InstrumentError
from pnps.geometry import SignalRegion, region_mask
__all__ = ["WindowSpec", "extract_observables"]
[docs]
@dataclass(frozen=True)
class WindowSpec:
"""A physical collection aperture (hole in the output mask plane).
Attributes
----------
holex, holey : float
Hole centre in the mask plane in m: where the signal appears,
:func:`pnps.geometry.signal_centre` (the TG signal corner is at
``(-d, -d)``).
holediam : float
Hole diameter in m.
zmask : float
Mask-plane distance from the focus in m.
apod : str
Edge profile, see :func:`pnps.beams.chromatic_mask`. The default,
``"rcos"``, is a raised cosine of compact support: the weight is exactly
zero outside the hole, so no window tail reaches the input arms.
apod_param : float or None
Edge parameter; None selects the conventional width for the profile
at setup time (three mask-plane pixels for ``"tanh"``, two for
``"rcos"``).
weighting : str
How the profile enters the observables.
- ``"amplitude"`` treats the profile as a physical amplitude filter:
the collected energy is ``sum |W E|^2 = sum W^2 |E|^2``. Because ``W^2`` is
not antisymmetric about the hole edge it under-counts the aperture — for the
smallest windows used here, by a quarter — while the re-imaged observable,
linear in ``W``, over-counts. The two observables therefore describe different
effective apertures.
- ``"quadrature"`` (default) treats the profile as a quadrature *weight* for
the integral over a genuinely hard hole: ``sum w |E|^2`` and
``|sum w E|^2``. One weight serves both observables, the enclosed
area is the nominal one to a part in ten thousand (see
:func:`pnps.beams.quadrature_holediam`), and with a
compact-support profile such as ``"rcos"`` the weight is exactly
zero outside the hole, so no window tail can reach the input arms.
The instrument's holes are hard, so this is the physically faithful
choice.
achromatic_wavelength : float or None
None (the default) for the physical hole, whose momentum-space footprint
scales with frequency (chromatic vignetting). A wavelength in m freezes the
footprint at that wavelength for every frequency: an achromatic window in
momentum space, a diagnostic that separates the vignetting from the edge.
"""
holex: float
holey: float
holediam: float
zmask: float
apod: str = "rcos"
apod_param: float | None = None
weighting: Literal["amplitude", "quadrature"] = "quadrature"
achromatic_wavelength: float | None = None
def _uniform_profile(
windows: tuple[WindowSpec, ...],
) -> tuple[str, bool, tuple[float, ...]]:
"""Return the profile shared by every window and its resolved widths.
The six windows of one instrument are holes in a single physical mask,
so they share an edge profile and a weighting convention; only their
positions and diameters differ. The reference reduction keeps the
requirement the fused host pass has (which additionally needs one centre
and one mask distance), so the two accept the same window sets.
Parameters
----------
windows : tuple of WindowSpec
The collection apertures, ``n_windows`` of them.
Returns
-------
apod : str
The shared edge profile.
quadrature : bool
True if the shared weighting is ``"quadrature"``.
apod_params : tuple of float
Each window's resolved edge parameter, in window order.
Raises
------
InstrumentError
If the windows do not share an edge profile and weighting, or if any
``apod_param`` is still unresolved.
"""
apods = {w.apod for w in windows}
weightings = {w.weighting for w in windows}
if len(apods) != 1 or len(weightings) != 1:
raise InstrumentError(
f"all collection windows must share one edge profile and "
f"weighting (they are holes in one mask); got apod={sorted(apods)}, "
f"weighting={sorted(weightings)}"
)
params = []
for w in windows:
if w.apod_param is None:
raise InstrumentError(
"WindowSpec.apod_param must be resolved before extraction"
)
params.append(w.apod_param)
return apods.pop(), weightings.pop() == "quadrature", tuple(params)