# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Per-element scalar bodies shared by the input former and the save-pass reduction.
The two host kernels this package still owns -- forming the delayed three-beamlet
input state (:mod:`pnps.form_input`) and reducing a saved plane to the measured
spectra (:mod:`pnps.reduce_numba`) -- both evaluate the chromatic hole model one
element at a time. They need the same mathematics, and need it *once*, so the bodies
live here and are inlined into both callers. The propagation itself is solprop's
(:mod:`pnps.bridge`); nothing here steps a field.
The transverse-momentum plane *is* the mask plane: a sample ``(kx, ky)`` at frequency
``omega`` maps to the mask-plane position ``(kx, ky) * zmask * c / omega``, so one
physical hole is a different k aperture at every frequency (see :mod:`pnps.beams`).
The analytic profiles are transcribed term for term from
:func:`pnps.beams.chromatic_mask`, which is the NumPy reference they are tested
against.
Notes
-----
The functions are ``@njit(inline="always")`` with no signatures, so they specialise on
first use and inline into their caller. They take and return scalars only -- no
arrays, no allocation. ``inline="always"`` matters: they are called once per element,
so a call that is not inlined would cost more than the arithmetic inside it.
"""
import cmath
import math
import os
import sys
import warnings
from typing import no_type_check
import numba
from numba import njit
from numba.core.config import NUMBA_NUM_THREADS # pyright: ignore[reportAttributeAccessIssue]
from scipy.constants import c
from solprop.backends import thread_budget
from pnps.exceptions import InstrumentError, ThreadBindingWarning
__all__ = [
"APOD_AREA",
"APOD_CODES",
"APOD_HARD",
"APOD_PLANCK",
"APOD_RCOS",
"APOD_SUPERGAUSS",
"APOD_TANH",
"admittance",
"apod_code",
"area_weight",
"hole_weight",
"launch_weight",
"mask_plane_radius",
"profile_weight",
"release_main_thread",
"size_thread_pool",
]
[docs]
def release_main_thread() -> bool:
"""Give the calling thread back the CPUs an OpenMP binding took from it.
Importing solprop's native backend starts its OpenMP runtime, which under
``OMP_PROC_BIND`` (with ``OMP_PLACES``) binds the main thread to its first place:
one CPU. Every thread the main thread starts afterwards inherits that CPU, numba's
OpenMP pool among them: a run then uses about one core of its allocation, and
steps five times slower at the production shape on 16 cores (LupoLab/pnps#7).
The native backend records the process's CPUs before it binds anything
(``solprop_native.PROCESS_CPUS``); when the calling thread now holds a strict
subset of them, this restores them and emits a
:class:`~pnps.exceptions.ThreadBindingWarning`. On 16 cores of an AMD EPYC 7513, a
bound run restored this way took 11.5 s per step, against 10.5 s unbound.
Returns
-------
bool
Whether the thread's CPUs were restored. False where there is nothing to undo:
the native backend is not loaded, the platform has no CPU affinity, or the
thread already holds every CPU the process had.
"""
granted = set(getattr(sys.modules.get("solprop_native"), "PROCESS_CPUS", ()))
if not granted or not hasattr(os, "sched_setaffinity"):
return False
held = os.sched_getaffinity(0)
if not held < granted:
return False
os.sched_setaffinity(0, granted)
warnings.warn(
ThreadBindingWarning(
f"OpenMP thread binding had confined the main thread to {len(held)} of "
f"the {len(granted)} CPUs this process may use; pnps restored them. "
"Leave OMP_PROC_BIND and OMP_PLACES unset: solprop chooses its own "
"placement, and a bound run otherwise uses about one core"
),
stacklevel=2,
)
return True
[docs]
def size_thread_pool() -> int:
"""Hold numba's thread pool within the process's thread budget.
The former and the reducer are numba's parallel kernels, and numba starts as many
threads as the processor count it sees, which in a container is commonly every
core of the host. solprop's ``solprop.backends.thread_budget()`` is the true
budget: the smallest of the CPU affinity, the physical cores, the control groups'
CPU quota and ``SOLPROP_THREADS``. The pool takes the smaller of that and numba's
own ceiling (``NUMBA_NUM_THREADS``), for the calling thread. It first undoes an
OpenMP binding of the calling thread (:func:`release_main_thread`), so the pool
runs on the process's CPUs, not on the one CPU the binding left.
Returns
-------
int
The pool's size now.
Examples
--------
>>> import numba
>>> size_thread_pool() == numba.get_num_threads()
True
"""
release_main_thread() # before numba's pool starts, which inherits the mask
threads = min(int(NUMBA_NUM_THREADS), thread_budget().threads)
numba.set_num_threads(threads)
return threads
# Integer codes for the edge profiles, so a kernel can branch on an int instead of a
# string. The names match :func:`pnps.beams.chromatic_mask`.
APOD_HARD = 0
APOD_SUPERGAUSS = 1
APOD_TANH = 2
APOD_RCOS = 3
APOD_AREA = 4
APOD_PLANCK = 5
#: The integer code of each edge profile name.
APOD_CODES: dict[str, int] = {
"hard": APOD_HARD,
"supergauss": APOD_SUPERGAUSS,
"tanh": APOD_TANH,
"rcos": APOD_RCOS,
"area": APOD_AREA,
"planck": APOD_PLANCK,
}
# Relative slack on the sub-pixel early-out in :func:`area_weight`. It only has to
# exceed the floating-point error in a hypot and a product -- a few ulps -- and 1e-12
# is about ten thousand of them. Widening the band that falls through to the exact
# supersampling can only cost time, never correctness, so it is deliberately generous.
_AREA_EARLY_OUT_SLACK = 1e-12
# The speed of light, bound at module level so the kernels see a compile-time constant.
_C = c
[docs]
def apod_code(apod: str) -> int:
"""Return the integer code of an edge profile, for branching inside a kernel.
Parameters
----------
apod : str
One of the names in :data:`APOD_CODES`.
Returns
-------
int
The profile's code.
Raises
------
InstrumentError
For an unknown profile name.
Examples
--------
>>> apod_code("rcos")
3
"""
if apod not in APOD_CODES:
raise InstrumentError(f"unknown apod {apod!r}; known: {sorted(APOD_CODES)}")
return APOD_CODES[apod]
[docs]
@njit(inline="always")
@no_type_check
def admittance(k2: complex, kperp2: float, omega: float) -> complex:
"""Return the dimensionless axial admittance ``c k_z / omega`` of one element.
The scalar body of :func:`pnps.flux.axial_admittance`: the principal root of
``k^2 - k_perp^2`` times ``c / omega``, zero where the column does not propagate
or the frequency is not positive.
Parameters
----------
k2 : complex
``(n(omega) omega / c)^2`` in rad^2/m^2.
kperp2 : float
``kx^2 + ky^2`` in rad^2/m^2.
omega : float
Absolute angular frequency, rad/s.
Returns
-------
complex
The admittance; its real part weights ``|E|^2`` in every measured energy.
"""
square = complex(k2.real - kperp2, k2.imag)
if square.real <= 0.0 or omega <= 0.0:
return 0.0j
return _C * cmath.sqrt(square) / omega
[docs]
@njit(inline="always")
@no_type_check
def launch_weight(k2: complex, kperp2: float, omega: float) -> float:
"""Return the factor that carries one air component into the slab at constant flux.
The scalar body of :func:`pnps.flux.launch_factor`, ``sqrt(eta_air / eta)``.
Parameters
----------
k2 : complex
The slab's ``(n(omega) omega / c)^2`` in rad^2/m^2.
kperp2 : float
``kx^2 + ky^2`` in rad^2/m^2.
omega : float
Absolute angular frequency, rad/s.
Returns
-------
float
The real, non-negative factor; zero where either medium does not carry the
component.
"""
air = admittance(complex((omega / _C) ** 2, 0.0), kperp2, omega).real
medium = admittance(k2, kperp2, omega).real
if air <= 0.0 or medium <= 0.0:
return 0.0
return math.sqrt(air / medium)
[docs]
@njit(inline="always")
@no_type_check
def mask_plane_radius(
kx_value: float,
ky_value: float,
factor: float,
holex: float,
holey: float,
) -> float:
"""Mask-plane distance of one element from a hole centre, in m.
Parameters
----------
kx_value, ky_value : float
Transverse momenta of this element, rad/m.
factor : float
The angle-to-position mapping ``zmask * c / omega``, m/(rad/m). The caller
hoists it out of the transverse loops, where it is constant.
holex, holey : float
Hole centre in the mask plane, m.
Returns
-------
float
``hypot(kx * factor - holex, ky * factor - holey)`` in m.
"""
return math.hypot(kx_value * factor - holex, ky_value * factor - holey)
[docs]
@njit(inline="always")
@no_type_check
def profile_weight( # noqa: PLR0911 - one return per profile, and early-outs
radius: float, holediam: float, apod_code: int, apod_param: float
) -> float:
"""Transmission of a radial edge profile at one mask-plane radius.
The analytic profiles of :func:`pnps.beams.chromatic_mask`, transcribed term for
term. ``"rcos"`` gets the one shortcut worth taking: it has *compact* support, so
outside the transition band the answer is exactly 1 or exactly 0 and the sine
need not be evaluated at all -- which is most elements.
Parameters
----------
radius : float
Mask-plane distance from the hole centre, m.
holediam : float
Hole diameter, m.
apod_code : int
One of ``APOD_HARD``, ``APOD_SUPERGAUSS``, ``APOD_TANH``, ``APOD_RCOS``,
``APOD_PLANCK``. ``APOD_AREA`` is not a radial profile -- see
:func:`area_weight`.
apod_param : float
Supergaussian order, or the tanh/raised-cosine/Planck width in m.
Returns
-------
float
Transmission in [0, 1].
"""
half = holediam / 2
if apod_code == APOD_HARD:
return 1.0 if radius <= half else 0.0
if apod_code == APOD_SUPERGAUSS:
return math.exp(-((2 * radius / holediam) ** apod_param))
if apod_code == APOD_TANH:
return (1 - math.tanh((radius - half) / apod_param)) / 2
if apod_code == APOD_PLANCK:
# Flat to the hole radius, falling over one width outside it with the
# C-infinity Planck taper of pnps.pulse.planck_taper.
s = (radius - half) / apod_param
if s <= 0.0:
return 1.0
if s >= 1.0:
return 0.0
z = 1.0 / s - 1.0 / (1.0 - s)
return 1.0 - 1.0 / (1.0 + math.exp(min(max(z, -700.0), 700.0)))
# APOD_RCOS, with its compact support used as an early-out.
t = (radius - half) / apod_param
if t <= -1.0:
return 1.0
if t >= 1.0:
return 0.0
return (1 - math.sin(math.pi * t / 2)) / 2
[docs]
@njit(inline="always")
@no_type_check
def area_weight( # noqa: PLR0913, PLR0917 - a scalar body: one element's operands
kx_value: float,
ky_value: float,
factor: float,
delta_kx: float,
delta_ky: float,
holex: float,
holey: float,
holediam: float,
sub: int,
) -> float:
"""Fraction of one k pixel lying inside a hard hole.
The exact hard aperture, antialiased by ``sub x sub`` supersampling of the pixel
-- the unbiased, parameter-free rendering, and what the production input masks
use.
Most elements need none of that arithmetic: the pixel maps to a mask-plane patch
whose half-diagonal bounds how far any subsample's radius can lie from the pixel
centre's, so a pixel wholly inside the hole is 1 and a pixel wholly outside is 0.
Only pixels straddling the edge are supersampled. The bound is widened by a
relative slack of 1e-12 -- thousands of ulps more than the rounding of a hypot --
so the shortcut is exact: anything that could round either way falls through to
the full loop.
Parameters
----------
kx_value, ky_value : float
Pixel-centre momenta, rad/m.
factor : float
Angle-to-position mapping ``zmask * c / omega``.
delta_kx, delta_ky : float
Momentum pixel pitch, rad/m.
holex, holey : float
Hole centre in the mask plane, m.
holediam : float
Hole diameter, m.
sub : int
Supersampling factor per axis (4 is well converged).
Returns
-------
float
Covered fraction in [0, 1].
"""
half = holediam / 2
centre = mask_plane_radius(kx_value, ky_value, factor, holex, holey)
# Outermost subsample offsets, hence the largest mask-plane deviation of a
# subsample from the pixel centre.
span = 0.5 - 0.5 / sub
reach = math.hypot(span * delta_kx * factor, span * delta_ky * factor)
reach *= 1.0 + _AREA_EARLY_OUT_SLACK
if centre + reach <= half:
return 1.0
if centre - reach > half:
return 0.0
covered = 0.0
for iy in range(sub):
off_y = ((iy + 0.5) / sub - 0.5) * delta_ky
for ix in range(sub):
off_x = ((ix + 0.5) / sub - 0.5) * delta_kx
radius = mask_plane_radius(
kx_value + off_x, ky_value + off_y, factor, holex, holey
)
if radius <= half:
covered += 1.0
return covered / (sub * sub)
[docs]
@njit(inline="always")
@no_type_check
def hole_weight( # noqa: PLR0913, PLR0917 - a scalar body: one element's operands
kx_value: float,
ky_value: float,
factor: float,
delta_kx: float,
delta_ky: float,
holex: float,
holey: float,
holediam: float,
apod_code: int,
apod_param: float,
sub: int,
) -> float:
"""Transmission of one hole at one element, whichever rendering it uses.
Dispatches between the pixel-area rendering and the radial profiles so a kernel
can form its input state without knowing which the configuration asked for. The
branch is on a loop-invariant integer.
Parameters
----------
kx_value, ky_value : float
Element momenta, rad/m.
factor : float
Angle-to-position mapping ``zmask * c / omega``.
delta_kx, delta_ky : float
Momentum pixel pitch, rad/m (used only by the area rendering).
holex, holey : float
Hole centre in the mask plane, m.
holediam : float
Hole diameter, m.
apod_code : int
One of the ``APOD_*`` codes.
apod_param : float
Profile parameter (ignored by ``APOD_AREA`` and ``APOD_HARD``).
sub : int
Supersampling factor for ``APOD_AREA`` (ignored otherwise).
Returns
-------
float
Transmission in [0, 1].
"""
if apod_code == APOD_AREA:
return area_weight(
kx_value,
ky_value,
factor,
delta_kx,
delta_ky,
holex,
holey,
holediam,
sub,
)
radius = mask_plane_radius(kx_value, ky_value, factor, holex, holey)
return profile_weight(radius, holediam, apod_code, apod_param)