Source code for pnps.exact_windows

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

"""Exact hard-disc collection windows for the field the nonlinearity generated.

A collection window is a hard hole: in momentum, at each frequency, a disc of radius
``R = (D/2) omega / (c z_mask)`` about ``k_c = (x_h, y_h) omega / (c z_mask)``. On the
momentum grid it has to be rendered, and every rendering
(:func:`pnps.beams.chromatic_mask`) carries a quadrature error that grows as the disc
spans fewer bins: a few 1e-4 of the trace's peak for a 0.5 mm window on the production
grid (``docs/windows.md``). This module removes that error for a field whose real-space
support is compact.

The field a window sees is the nonlinear part ``N`` of the state
(:func:`pnps.simulate.visit_nonlinear`): behind compact input holes no linear light
reaches a signal window. ``N`` is driven by products of focal fields, so it is confined
near the focus, far inside the transverse box. A field of compact support on the grid's
periodic real-space box has a spectrum that is a finite Fourier series in ``k``,

``N(k) = sum_l n_l exp(-i k x_l)``,

with ``n_l`` its real-space samples. Integrals of such a series over a disc are exact:

- *on-axis spectrum* (linear in ``N``): ``int_disc N(k) exp(i k x_c) d^2k = sum_l n_l
  W(x_c - x_l)``, with ``x_c`` the grid's centre and ``W(r) = int_disc exp(-i k r) d^2k
  = exp(-i k_c r) 2 pi R J1(R |r|) / |r|`` the disc's transform;
- *collected energy* (quadratic): ``eta(k) |N(k)|^2`` is the series of the
  autocorrelation ``A = ifft2(eta |N|^2)`` over the lags ``Delta x``, exact when that
  autocorrelation does not wrap round the box, that is when ``N`` occupies less than
  half the box in each direction; then ``int_disc eta |N|^2 d^2k = sum_Dx A(Dx)
  W(Dx)``.

Both sums are linear in the momentum-grid samples (of ``N``, and of ``eta |N|^2``), so
each is a fixed weight on the grid, one per window and frequency: the disc's indicator
interpolated by the grid's own kernel. :class:`ExactWindows` builds these weights once
and applies them to any number of planes at the cost of a grid sum.

The admittance ``eta`` (:mod:`pnps.flux`) is smooth across a window, so multiplying by
it keeps the support compact. Both results are returned in the units of the grid sums of
:func:`pnps.extraction.extract_observables` (an integral over ``d^2k`` divided by the
pixel area ``dk^2``), so the two are compared directly. :func:`wrap_share` reports the
share of ``|N|^2`` in the outer part of the box, the measure of how well the support
condition holds.
"""

from concurrent.futures import ThreadPoolExecutor

import numpy as np
from jaxtyping import Complex, Float, Int
from scipy.constants import c
from scipy.special import j1
from solprop.backends import thread_budget

from pnps.extraction import WindowSpec
from pnps.flux import axial_admittance
from pnps.grids import SpaceGrid

__all__ = [
    "ExactWindows",
    "disc_transform",
    "exact_window_spectra",
    "nyquist_reach",
    "wrap_share",
]


[docs] def disc_transform( radius: float, centre: tuple[float, float], rx: Float[np.ndarray, "*_"], ry: Float[np.ndarray, "*_"], ) -> Complex[np.ndarray, "*_"]: """Return the disc's transform, the integral of ``exp(-i k r)`` over the disc. Parameters ---------- radius : float The disc's radius in momentum, rad/m. centre : tuple of float Its centre ``(k_x, k_y)``, rad/m. rx, ry : numpy.ndarray The displacement ``r``, m; the two broadcast together. Returns ------- numpy.ndarray ``exp(-i k_c . r) 2 pi R J1(R |r|) / |r|``, which is ``pi R^2`` at ``r = 0``. Examples -------- >>> import numpy as np >>> float(disc_transform(2.0, (0.0, 0.0), np.array(0.0), np.array(0.0)).real) 12.566370614359172 """ r = np.hypot(rx, ry) safe = np.where(r > 0.0, r, 1.0) profile = np.where( r > 0.0, 2 * np.pi * radius * j1(radius * safe) / safe, np.pi * radius**2 ) return np.asarray(profile * np.exp(-1j * (centre[0] * rx + centre[1] * ry)))
[docs] class ExactWindows: """The exact hard-disc weights of a set of windows on the run's momentum grid. Both sums of the module's introduction are fixed linear functionals of the momentum-grid samples. Writing the lag sum of the energy back in momentum, ``sum_Dx A(Dx) W(Dx) = sum_k eta |N(k)|^2 M(k)`` with ``M = ifft2(W)`` over the box's lags: the weight ``M`` is the disc's indicator interpolated by the grid's own (Dirichlet) kernel, and the on-axis amplitude is ``sum_k N(k) M(k)`` with the phase that centres it. So a window's exact hard disc is a mask, one per window and frequency, built once and applied to every plane at the cost of a grid sum, like any other rendering. Unlike the others it is not compact: its tails reach every bin, which is why it is exact only for a field of compact real-space support, the nonlinear part ``N`` and not the whole state with its input arms. The masks take ``n_bins * n_windows * n^2`` doubles: 6 GB for six windows over the 216 bins of 190 to 400 nm on the 768 x 768 production grid. Parameters ---------- sgrid : SpaceGrid The transverse grid. omega : numpy.ndarray Absolute angular frequency, FFT-ordered, ``(nt,)``, rad/s. k2 : numpy.ndarray The material wavenumber squared, ``(nt,)``, complex, rad^2/m^2, zero off the band (the admittance is zero there). windows : tuple of WindowSpec The collection windows; only their position, diameter, mask distance and achromatic wavelength enter: each is its nominal hard hole. bins : numpy.ndarray or None, optional The frequency bins to integrate; None takes every positive frequency on the band. The others are returned as zero. """ def __init__( self, sgrid: SpaceGrid, omega: Float[np.ndarray, " n_omega"], k2: Complex[np.ndarray, " n_omega"], windows: tuple[WindowSpec, ...], bins: Int[np.ndarray, " n_bins"] | None = None, ) -> None: if bins is None: bins = np.flatnonzero((omega > 0.0) & (np.real(k2) > 0.0)) self.bins = np.asarray(bins, dtype=int) self._n, self._nt = sgrid.n, len(omega) self._omega = np.asarray(omega, dtype=float) self._k2 = np.asarray(k2, dtype=complex) self._kperp2 = sgrid.kx[:, None] ** 2 + sgrid.kx[None, :] ** 2 n = self._n # The phase (-1)^(i + j) moves the box's lag origin to its centre (index n/2), # where the instrument places its beams. self._sign = (-1.0) ** (np.arange(n)[:, None] + np.arange(n)[None, :]) self.masks = np.empty((len(self.bins), len(windows), n, n)) def _build(i: int) -> None: """Fill one bin's masks.""" self.masks[i] = _disc_masks( sgrid, float(self._omega[self.bins[i]]), windows ) with ThreadPoolExecutor(max_workers=_workers()) as pool: list(pool.map(_build, range(len(self.bins))))
[docs] def reduce( self, nonlinear: Complex[np.ndarray, "n_y n_x n_omega"] ) -> tuple[ Float[np.ndarray, "n_windows n_omega"], Float[np.ndarray, "n_windows n_omega"] ]: """Integrate one plane's nonlinear field over each window's hard disc. Parameters ---------- nonlinear : numpy.ndarray The nonlinear part of the state, ``(n, n, nt)``: zero at the input arms, and of compact real-space support (:func:`wrap_share`). Returns ------- tuple of numpy.ndarray ``(i_omega_win, i_omega_reimaged)``, each ``(n_windows, nt)``: the collected flux and the on-axis spectrum paired with its magnetic closure, as :func:`pnps.extraction.extract_observables` defines them, in its units. """ n_windows = self.masks.shape[1] energy = np.zeros((n_windows, self._nt)) axis = np.zeros((n_windows, self._nt)) n2 = self._n**2 def _integrate(i: int) -> None: """Fill one frequency bin's column of both results.""" b = int(self.bins[i]) om = float(self._omega[b]) y = axial_admittance( self._k2[b : b + 1], self._kperp2[:, :, None], np.array([om]) )[:, :, 0] field = nonlinear[:, :, b] centred = self._sign * field magnetic = np.conj(y) * centred # One real product for the five real sums: the flux density and the real # and imaginary parts of the amplitude and of its magnetic closure. columns = np.stack( ( np.real(y) * np.abs(field) ** 2, centred.real, centred.imag, magnetic.real, magnetic.imag, ), axis=-1, ).reshape(n2, 5) # fmt: skip sums = self.masks[i].reshape(n_windows, n2) @ columns energy[:, b] = sums[:, 0] amplitude = (sums[:, 1] + 1j * sums[:, 2]) / n2 closure = (sums[:, 3] + 1j * sums[:, 4]) / n2 axis[:, b] = np.real(amplitude * np.conj(closure)) with ThreadPoolExecutor(max_workers=_workers()) as pool: list(pool.map(_integrate, range(len(self.bins)))) return energy, axis
[docs] def exact_window_spectra( nonlinear: Complex[np.ndarray, "n_y n_x n_omega"], sgrid: SpaceGrid, omega: Float[np.ndarray, " n_omega"], k2: Complex[np.ndarray, " n_omega"], windows: tuple[WindowSpec, ...], bins: Int[np.ndarray, " n_bins"] | None = None, ) -> tuple[ Float[np.ndarray, "n_windows n_omega"], Float[np.ndarray, "n_windows n_omega"] ]: """Integrate a compact field over each window's exact hard disc, once. The one-plane form of :class:`ExactWindows`, which builds the masks and applies them; build an :class:`ExactWindows` to reduce several planes with one set. Parameters ---------- nonlinear : numpy.ndarray The nonlinear part of the state, ``(n, n, nt)``: zero at the input arms, and of compact real-space support (:func:`wrap_share`). sgrid : SpaceGrid The transverse grid. omega : numpy.ndarray Absolute angular frequency, FFT-ordered, ``(nt,)``, rad/s. k2 : numpy.ndarray The material wavenumber squared, ``(nt,)``, complex, rad^2/m^2. windows : tuple of WindowSpec The collection windows. bins : numpy.ndarray or None, optional The frequency bins to integrate; None takes every positive frequency on the band. Returns ------- tuple of numpy.ndarray ``(i_omega_win, i_omega_reimaged)``, each ``(n_windows, nt)``. """ return ExactWindows(sgrid, omega, k2, windows, bins).reduce(nonlinear)
[docs] def nyquist_reach( sgrid: SpaceGrid, omega: Float[np.ndarray, " n_bins"], windows: tuple[WindowSpec, ...], ) -> str | None: """Return how a window's disc reaches the grid's Nyquist limit, or None. The disc's transform takes the same value on every lag of the grid when its centre moves by ``2 pi / dx``, so a disc that reaches ``|k| = pi / dx`` along either axis integrates part of a periodic copy of the spectrum instead of the light beyond the grid, which the grid cannot hold. solprop refuses such an exact aperture (SEP 53); this is the same test, made before anything is built. Parameters ---------- sgrid : SpaceGrid The transverse grid. omega : numpy.ndarray The frequencies the windows collect, rad/s. windows : tuple of WindowSpec The collection windows. Returns ------- str or None The first window that reaches the limit and the wavelength from which it does, or None. """ limit = np.pi / sgrid.delta_x omega = np.asarray(omega, dtype=float) for j, w in enumerate(windows): mapped = ( omega if w.achromatic_wavelength is None else np.full_like(omega, 2 * np.pi * c / w.achromatic_wavelength) ) reach = (max(abs(w.holex), abs(w.holey)) + w.holediam / 2) * mapped crossing = omega[reach / (c * w.zmask) >= limit] if crossing.size: return ( f"window {j + 1}'s exact disc reaches the transverse Nyquist limit " f"pi/dx = {limit:.4g} rad/m at wavelengths from " f"{2 * np.pi * c / crossing.min() * 1e9:.1f} nm down, where it would " "integrate a periodic copy of the spectrum: sample the transverse " "grid more finely (a larger n_transverse at the same r_max) or narrow " "the band" ) return None
def _workers() -> int: """Return the threads this process may run: solprop's budget. Not the calling thread's affinity: with ``OMP_PROC_BIND`` set, importing solprop's native backend binds the main thread to one CPU, which solprop's budget undoes. """ return thread_budget().threads def _disc_masks( sgrid: SpaceGrid, om: float, windows: tuple[WindowSpec, ...] ) -> Float[np.ndarray, "n_windows n n"]: """Return each window's exact hard-disc weight on the momentum grid at ``om``. The disc's transform ``W`` on the box's lags (``-n/2`` to ``n/2 - 1`` samples, centred), taken back to momentum. Its imaginary part comes only from the lag ``-n/2``, which has no partner at ``+n/2``, and meets only a field at the box's edge; it is dropped. """ n, dx = sgrid.n, sgrid.delta_x dk = float(sgrid.kx[1] - sgrid.kx[0]) lags = (np.arange(n) - n // 2) * dx # |lag| along each axis indexes the jinc, evaluated once on a quadrant. fold = np.abs(np.arange(n) - n // 2) quadrant = np.arange(n // 2 + 1) * dx masks = np.empty((len(windows), n, n)) phases: dict[tuple[float, float], np.ndarray] = {} for iw, w in enumerate(windows): mapped = ( om if w.achromatic_wavelength is None else 2 * np.pi * c / w.achromatic_wavelength ) scale = mapped / (c * w.zmask) radius = w.holediam / 2 * scale centre = (w.holex * scale, w.holey * scale) # Windows that share a centre (holes in one mask) share the phase factor; rows # are y, columns x. if centre not in phases: phases[centre] = np.exp( -1j * (centre[0] * lags[None, :] + centre[1] * lags[:, None]) ) transform = _jinc(radius, quadrant)[np.ix_(fold, fold)] * phases[centre] masks[iw] = np.real(np.fft.ifft2(np.fft.ifftshift(transform))) / dk**2 return masks def _jinc(radius: float, offsets: Float[np.ndarray, " m"]) -> Float[np.ndarray, "m m"]: """Return ``2 pi R J1(R r) / r`` on the square of ``offsets``, ``pi R^2`` at 0.""" r = np.hypot(offsets[None, :], offsets[:, None]) safe = np.where(r > 0.0, r, 1.0) return np.where( r > 0.0, 2 * np.pi * radius * j1(radius * safe) / safe, np.pi * radius**2 )
[docs] def wrap_share( nonlinear: Complex[np.ndarray, "n_y n_x n_omega"], fraction: float = 0.25 ) -> float: """Return the share of ``|N|^2`` beyond ``fraction`` of the box from its centre. The collected energy of :func:`exact_window_spectra` is exact when ``N`` occupies less than half the box in each direction (its autocorrelation then does not wrap), so with the default ``fraction`` this is the energy outside that region. Parameters ---------- nonlinear : numpy.ndarray The nonlinear part of the state, ``(n, n, nt)``. fraction : float, optional The half-width of the central square, as a fraction of the box, in (0, 0.5). Returns ------- float The share of ``sum |N(x)|^2`` outside the central square, summed over frequency; zero for a zero field. """ real = np.fft.ifft2(nonlinear, axes=(0, 1)) n = real.shape[0] distance = np.abs(np.arange(n) - n // 2) outside = (distance[:, None] > fraction * n) | (distance[None, :] > fraction * n) power = np.sum(np.abs(real) ** 2, axis=-1) total = float(power.sum()) return float(power[outside].sum()) / total if total > 0.0 else 0.0