Source code for pnps.extraction

# 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)
[docs] def extract_observables( # noqa: PLR0913 - the state, its axes, windows and measure e: Complex[np.ndarray, "n_y n_x n_omega"], ky: Float[np.ndarray, " n_y"], kx: Float[np.ndarray, " n_x"], omega: Float[np.ndarray, " n_omega"], windows: tuple[WindowSpec, ...], region: SignalRegion | None = None, *, admittance: Complex[np.ndarray, "n_y n_x n_omega"] | None = None, ) -> tuple[ Float[np.ndarray, "n_windows n_omega"], Float[np.ndarray, "n_windows n_omega"], Float[np.ndarray, " n_omega"], ]: """Reduce one saved state to the per-window spectra (the NumPy reference). A run reduces its planes with the fused host pass of :mod:`pnps.reduce_numba`; this is the plain array expression of the same reductions, one window at a time, against which that pass is tested. It materialises one mask and one masked field per window, so it is for test grids. Parameters ---------- e : numpy.ndarray Spectral state ``(n, n, nt)``. ky, kx, omega : numpy.ndarray Grid axes (FFT-ordered). windows : tuple of WindowSpec Collection apertures with resolved (non-None) ``apod_param``, sharing one ``apod`` and one ``weighting``. region : SignalRegion or None, optional The momentum region ``i_omega_full`` sums; None for the TG quadrant ``kx, ky < 0``. admittance : numpy.ndarray or None, optional The medium's axial admittance at every element (:mod:`pnps.flux`): its real part weights ``|E|^2`` and its conjugate forms the on-axis closure (the flux measure). None weights every element by 1 (the field measure). Returns ------- tuple of numpy.ndarray ``(i_omega_win, i_omega_reimaged, i_omega_full)`` with shapes ``(n_windows, nt)``, ``(n_windows, nt)`` and ``(nt,)``. Raises ------ InstrumentError If the windows do not share an edge profile and weighting, or if any ``apod_param`` is still unresolved. """ apod, quadrature, apod_params = _uniform_profile(windows) n_y, n_x = e.shape[-3], e.shape[-2] # Centre pixel of ifft2 == mean weighted by (-1)^(iy+ix), for even n. sign = (-1.0) ** (np.arange(n_y)[:, None] + np.arange(n_x)[None, :]) y = np.ones(e.shape) if admittance is None else admittance power = np.real(y) * np.abs(e) ** 2 i_win, i_reimaged = [], [] for w, param in zip(windows, apod_params, strict=True): # 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. diam = ( quadrature_holediam(w.holediam, w.apod, param) if quadrature else w.holediam ) # An achromatic window maps every positive frequency as its one wavelength. omega_map = ( omega if w.achromatic_wavelength is None else np.where(omega > 0.0, 2 * np.pi * c / w.achromatic_wavelength, omega) ) mask = chromatic_mask( ky, kx, omega_map, w.holex, w.holey, diam, w.zmask, apod, param ) we = mask * e # Quadrature: w weights the energy density once. Amplitude: the profile # filters the field, so the energy carries it squared. i_win.append( np.sum(mask * power, axis=(0, 1)) if quadrature else np.sum(np.real(y) * np.abs(we) ** 2, axis=(0, 1)) ) # The on-axis amplitude paired with its magnetic closure, Re(A conj(G)). centre = np.sum(sign[:, :, None] * we, axis=(0, 1)) / (n_y * n_x) closure = np.sum(sign[:, :, None] * np.conj(y) * we, axis=(0, 1)) / (n_y * n_x) i_reimaged.append(np.real(centre * np.conj(closure))) if region is None: i_omega_full = np.sum(power[n_y // 2 :, n_x // 2 :, :], axis=(0, 1)) else: inside = region_mask(region, ky, kx) i_omega_full = np.sum(np.where(inside, power, 0.0), axis=(0, 1)) return np.array(i_win), np.array(i_reimaged), i_omega_full