Source code for pnps.absorber

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

"""The spectral absorber: band-edge ramps and the group-delay lap budget.

All dissipation is inside the exact linear operator. This module tabulates its
spectral part, ``gamma_omega``, once per configuration (:func:`pnps.setup.build_setup`);
solprop applies it as its absorber's spectral rate (:mod:`pnps.bridge`), and the NumPy
reference model (:mod:`pnps.reference`) applies the same table. The lap budget's share,
``gamma_lap``, is kept apart, so that what it removes is reported apart from the band
edges (:func:`lap_free_band`, :func:`required_trange`, :func:`lap_loss_share`).
:func:`wrap_coupling` reads the same table to bound what light that wraps the window
can do at a delay point (:func:`pnps.simulate.run_delay_point` refuses a delay where it
could do too much).
"""

import logging
from typing import NamedTuple

import numpy as np
from jaxtyping import Bool, Complex, Float
from scipy.constants import c
from solprop.spatial_absorber import safety_ramp_strength

from pnps.exceptions import ConfigError
from pnps.grids import SpaceGrid, TimeGrid
from pnps.materials import beta1_ref, silica_index

__all__ = [
    "WRAP_COUPLING_LIMIT",
    "SpectralRates",
    "band_edges",
    "group_walkoff",
    "lap_free_band",
    "lap_loss_share",
    "lap_lost",
    "required_trange",
    "spectral_absorber",
    "transverse_rate",
    "transverse_strength",
    "wrap_attenuation",
    "wrap_coupling",
]

logger = logging.getLogger(__name__)

#: The largest wrap coupling (:func:`wrap_coupling`) a delay point may have beyond
#: three quarters of ``time_headroom``. Light radiated by a nonlinear polarization of
#: ``1e-5`` of the input's peak is at most ``1e-5`` of the signal's peak amplitude, so
#: its interference moves a trace by at most ``2e-5`` of the trace's peak, inside the
#: ``3e-5`` of the peak that the production step and windows are chosen for
#: (:doc:`/accuracy`).
WRAP_COUPLING_LIMIT = 1e-5


[docs] class SpectralRates(NamedTuple): """The spectral absorber, whole and by part. Attributes ---------- gamma_omega : numpy.ndarray The amplitude rate the operator applies, 1/m, ``(nt,)``: the band edges' rate plus :attr:`gamma_lap`. gamma_lap : numpy.ndarray The lap budget's share of it, 1/m, ``(nt,)``: what it adds above the band edges' ramps. gd_band : numpy.ndarray The 0/1 indicator of the bins the lap budget absorbs, ``(nt,)``. """ gamma_omega: Float[np.ndarray, " n_omega"] gamma_lap: Float[np.ndarray, " n_omega"] gd_band: Float[np.ndarray, " n_omega"]
def _edge_ramp(s: Float[np.ndarray, "*shape"]) -> Float[np.ndarray, "*shape"]: """Evaluate the raised-cosine ramp 0 -> 1 for s in [0, 1], clipped outside. Parameters ---------- s : numpy.ndarray Dimensionless ramp coordinate, any shape; values outside [0, 1] are clipped. Returns ------- numpy.ndarray ``(1 - cos(pi s)) / 2``, in [0, 1], the shape of ``s``. """ s = np.clip(s, 0.0, 1.0) return 0.5 * (1 - np.cos(np.pi * s))
[docs] def spectral_absorber( tgrid: TimeGrid, thickness: float, gamma_max: float = 5e6, time_headroom: float = 40e-15, ) -> SpectralRates: """Build the spectral absorber: band-edge ramps and the group-delay lap budget. The absorber ``gamma_omega`` is the pointwise maximum of two criteria: - *band edges*: zero on the physical band ``[omega_min, omega_max]``, ramping to ``gamma_max`` over ``[omega_min/2, omega_min]`` and ``[omega_max, 1.1 omega_max]``, ``gamma_max`` beyond; - *group-delay (lap) budget*: on a periodic time window, walked-off light is represented exactly and harmlessly (the Kerr response is local in time, the observables are per-frequency) *until it wraps a full period and lands back on the pulse*. Frequencies whose walk-off relative to the co-moving frame, ``|beta1(omega) - beta1_ref| * thickness``, exceeds the lap budget -- the full window length minus twice ``time_headroom`` (the protected half-width around t = 0 holding the pulse and the delay scan) -- are therefore absorbed, ramping to full strength over one further ``time_headroom`` of walk-off. In silica this bites only the extreme-DUV band edge, where the group index rises steeply. The fraction of field power sitting in the absorbed bins is reported per save (``gd_band_power``): if it is not small, the time window is too short for full spectral fidelity -- enlarge ``trange`` rather than trusting the run. ``gamma_max`` is a property of the configured ODE -- deliberately *not* derived from the step size, so that step-size studies converge to one answer. The walk-off is :func:`group_walkoff`. The lap budget's share is the rate it adds above the band edges, so the whole is the edges' rate plus that share, bit for bit as solprop sums its collar and a custom rate (:func:`solprop.boundaries.custom_absorber`). Parameters ---------- tgrid : TimeGrid The temporal grid. thickness : float Total propagation distance in m (sets the group-delay budget). gamma_max : float Peak amplitude absorption rate of the edge absorbers in 1/m. time_headroom : float Protected half-width around t = 0 (pulse support plus the delay scan), in s. Returns ------- SpectralRates The amplitude rate in 1/m, the lap budget's share of it and the 0/1 indicator of the bins the lap budget absorbs, each ``(nt,)``. Raises ------ ConfigError If the time window is too small to leave any lap budget. """ window = tgrid.nt * tgrid.delta_t budget = window - 2 * time_headroom if budget <= 0: raise ConfigError( f"time window ({window:.3g} s) leaves no lap budget after 2 x " f"{time_headroom:.3g} s protected region; enlarge trange" ) walkoff = group_walkoff(tgrid, thickness) gamma_gd = _edge_ramp((walkoff - budget) / time_headroom) edges = band_edges(tgrid, gamma_max) gamma_lap = np.maximum(edges, gamma_max * gamma_gd) - edges return SpectralRates( gamma_omega=edges + gamma_lap, gamma_lap=gamma_lap, gd_band=(gamma_gd > 0).astype(float), )
[docs] def band_edges(tgrid: TimeGrid, gamma_max: float) -> Float[np.ndarray, " n_omega"]: """Return the band edges' amplitude rate, the spectral absorber less the lap budget. Zero on the physical band ``[omega_min, omega_max]``, rising as a raised cosine to ``gamma_max`` over ``[omega_min/2, omega_min]`` and ``[omega_max, 1.1 omega_max]``, and ``gamma_max`` beyond. :func:`spectral_absorber` and the bridge both take it from here, so solprop's sum of it and the lap budget's share is this package's rate bit for bit. Parameters ---------- tgrid : TimeGrid The temporal grid. gamma_max : float The peak amplitude rate, 1/m. Returns ------- numpy.ndarray The rate, 1/m, ``(nt,)``. """ omega = tgrid.omega w_lo0, w_lo1 = tgrid.omega_min / 2, tgrid.omega_min w_hi1, w_hi0 = tgrid.omega_max, 1.1 * tgrid.omega_max return gamma_max * np.maximum( _edge_ramp((w_lo1 - omega) / (w_lo1 - w_lo0)), _edge_ramp((omega - w_hi1) / (w_hi0 - w_hi1)), )
[docs] def group_walkoff(tgrid: TimeGrid, thickness: float) -> Float[np.ndarray, " n_omega"]: """Return each frequency's group-delay walk-off over the slab, s. ``|beta1(omega) - beta1_ref| * thickness`` relative to the co-moving frame, with ``beta1`` by a symmetric finite difference of ``beta = Re n(omega) omega / c`` (truncation about 1e-12). Evaluated on the active band only: the bins outside it are held by the band-edge ramps, and read zero. Parameters ---------- tgrid : TimeGrid The temporal grid. thickness : float The slab's thickness, m. Returns ------- numpy.ndarray The walk-off, s, ``(nt,)``. """ walkoff = np.zeros(tgrid.nt) walkoff[tgrid.sidx] = _walkoff_at(tgrid.omega[tgrid.sidx], tgrid.lam0, thickness) return walkoff
def _walkoff_at( omega: Float[np.ndarray, " n"], lam0: float, thickness: float ) -> Float[np.ndarray, " n"]: """Return the walk-off over the slab at given frequencies, s. Parameters ---------- omega : numpy.ndarray Angular frequencies, rad/s. lam0 : float The carrier wavelength that sets the co-moving frame, m. thickness : float The slab's thickness, m. Returns ------- numpy.ndarray ``|beta1(omega) - beta1_ref| * thickness``, s. """ d_omega = 1e-6 * 2 * np.pi * c / lam0 def beta_of(w: Float[np.ndarray, "*shape"]) -> Float[np.ndarray, "*shape"]: """Return the silica propagation constant ``Re n(omega) omega / c``. Parameters ---------- w : numpy.ndarray Angular frequency, rad/s, any shape. Returns ------- numpy.ndarray The propagation constant, rad/m, the shape of ``w``. """ return np.real(silica_index(w)) * w / c beta1 = (beta_of(omega + d_omega) - beta_of(omega - d_omega)) / (2 * d_omega) return np.abs(beta1 - beta1_ref(lam0)) * thickness
[docs] def required_trange( tgrid: TimeGrid, thickness: float, time_headroom: float, ) -> float: """Return the shortest time window whose lap budget absorbs nothing in band. The lap budget starts to absorb a frequency once its walk-off exceeds the window less twice ``time_headroom``, and ramps to full strength over one more ``time_headroom``. So a window of ``3 time_headroom`` plus the largest walk-off over the requested band ``[omega_min, omega_max]``, limits included, absorbs nothing the spectrometer would see. The walk-off does not depend on the window, so any grid of the configuration gives the same answer. Parameters ---------- tgrid : TimeGrid A temporal grid of the configuration, for its band and frequencies. thickness : float The slab's thickness, m. time_headroom : float The protected half-width around t = 0, s. Returns ------- float The window length ``trange``, s. """ # The walk-off grows towards both ends of the band, so its largest value is at # a limit: evaluated there, not at the nearest bin, so that the answer does not # depend on how the grid samples the band. limits = np.array([tgrid.omega_min, tgrid.omega_max]) walkoff = _walkoff_at(limits, tgrid.lam0, thickness) inside = group_walkoff(tgrid, thickness)[_in_band(tgrid)] return 3 * time_headroom + float(max(np.max(walkoff), np.max(inside)))
[docs] def wrap_attenuation( tgrid: TimeGrid, thickness: float, gamma_omega: Float[np.ndarray, " n_omega"], walk: Float[np.ndarray, "*shape"], ) -> Float[np.ndarray, "*shape"]: """Return the least attenuation of any light by the time it has walked a distance. Light of a bin with walk-off ``w`` over the slab moves ``w / thickness`` per metre relative to the co-moving frame (:func:`group_walkoff`), so to walk ``x`` it must cross ``x thickness / w`` of slab. Over that it loses ``gamma x thickness / w`` amplitude e-folds to the spectral absorber, with ``gamma`` the whole rate (the band edges and the lap budget). Only a bin with ``w >= x`` walks ``x`` inside the slab, so the least attenuation of light that has walked ``x`` is the smallest of that over those bins: infinite when none walks so far, zero for ``x <= 0`` (no walk at all). It is non-decreasing in ``x``. Parameters ---------- tgrid : TimeGrid The temporal grid. thickness : float The slab's thickness, m. gamma_omega : numpy.ndarray The spectral absorber's amplitude rate, 1/m, ``(nt,)`` (:attr:`SpectralRates.gamma_omega`). walk : numpy.ndarray The walked distances, s, any shape. Returns ------- numpy.ndarray The attenuation in amplitude e-folds (nepers), the shape of ``walk``. """ walkoff = group_walkoff(tgrid, thickness) # The bins outside the active band read zero and hold nothing. moving = walkoff > 0.0 order = np.argsort(walkoff[moving])[::-1] walks = walkoff[moving][order] # descending # The smallest gamma / w over the bins that walk at least as far as each one. least = np.minimum.accumulate((gamma_omega[moving] / walkoff[moving])[order]) walk = np.asarray(walk, dtype=float) reaching = np.searchsorted(-walks, -walk, side="right") rate = np.where(reaching > 0, least[np.maximum(reaching - 1, 0)], np.inf) with np.errstate(invalid="ignore"): return np.where(walk > 0.0, walk * thickness * rate, 0.0)
[docs] def wrap_coupling( tgrid: TimeGrid, thickness: float, gamma_omega: Float[np.ndarray, " n_omega"], e_omega: Complex[np.ndarray, " n_omega"], tau: float, ) -> float: """Bound the nonlinear polarization wrapped light can drive at a delay point. A delay point holds two pulse positions, the delay-free arms and the delayed one, ``|tau|`` apart on the periodic window of length ``T``. Light leaving one pulse at time ``t_s`` (relative to that pulse) reaches time ``t_t`` of the other through the wrap once it has walked ``T - |tau| -+ (t_t - t_s)``, depending on which way it walks; the shorter way is ``x = T - |tau| - |t_t - t_s|``, and by then it has lost at least :func:`wrap_attenuation` ``A(x)``. On an infinite line it would never meet that pulse. Where it lands, it drives a Kerr polarization of at most its field times the intensity there, so in units of the input's peak polarization the coupling is ``C = max over t_s, t_t of sqrt(P(t_s)) P(t_t) exp(-A(x))``, with ``P`` the input's temporal power profile over its peak. Its field and its intensity both count: a pulse's own wings carry light, and its wings and core both drive. The profile is that of the 1-D input spectrum every arm carries (the pulse, its chirp, or an injected field); the chromatic holes, real filters per transverse sample, are not part of it. Light generated in the slab is covered too: it is born where the pulses are, at most as strong as they, and loses the same e-folds as it walks. The bound is the same for every layout and window, and makes no use of which arms a signal needs. Parameters ---------- tgrid : TimeGrid The temporal grid. thickness : float The slab's thickness, m. gamma_omega : numpy.ndarray The spectral absorber's amplitude rate, 1/m, ``(nt,)``. e_omega : numpy.ndarray The 1-D input spectrum, ``(nt,)``, in this package's storage convention (:attr:`pnps.setup.Setup.e_omega_input`): its inverse DFT is the field on the centred time axis. tau : float The delay, s. Returns ------- float The coupling ``C``, in [0, 1]; 1 when the pulses meet through the wrap without walking at all. """ power = np.abs(np.fft.ifft(e_omega)) ** 2 power /= np.max(power) field = np.sqrt(power) nt = tgrid.nt # The strongest source-field x target-intensity product at each separation k # samples, either way round. The profile is taken on the centred axis, not # periodically: the pulse is centred, and the separations within it are short. strongest = np.array( [ max( float(np.max(field[: nt - k] * power[k:])), float(np.max(field[k:] * power[: nt - k])), ) for k in range(nt) ] ) walk = nt * tgrid.delta_t - abs(tau) - np.arange(nt) * tgrid.delta_t attenuation = wrap_attenuation(tgrid, thickness, gamma_omega, walk) return float(np.max(strongest * np.exp(-attenuation)))
[docs] def lap_free_band( tgrid: TimeGrid, gamma_lap: Float[np.ndarray, " n_omega"] ) -> tuple[float, float]: """Return the wavelengths between which the lap budget absorbs nothing. The bins of the requested band ``[omega_min, omega_max]`` that the lap budget leaves alone, taken outward from the carrier until the first it absorbs. Parameters ---------- tgrid : TimeGrid The temporal grid. gamma_lap : numpy.ndarray The lap budget's rate (:attr:`SpectralRates.gamma_lap`), ``(nt,)``. Returns ------- tuple of float ``(lam_short, lam_long)`` in m: the shortest and longest wavelengths of the untouched band. They equal the requested limits' bins when the lap budget absorbs nothing in band. """ omega = tgrid.omega band = _in_band(tgrid) absorbed = band & (gamma_lap > 0.0) above = absorbed & (omega > tgrid.omega0) below = absorbed & (omega < tgrid.omega0) top = float(np.min(omega[above])) if above.any() else np.inf bottom = float(np.max(omega[below])) if below.any() else -np.inf kept = omega[band & (omega < top) & (omega > bottom)] return 2 * np.pi * c / float(np.max(kept)), 2 * np.pi * c / float(np.min(kept))
[docs] def lap_lost( beam: Float[np.ndarray, "n_z n_omega"], z: Float[np.ndarray, " n_z"], gamma_omega: Float[np.ndarray, " n_omega"], gamma_lap: Float[np.ndarray, " n_omega"], ) -> Float[np.ndarray, " n_omega"]: """Return the energy per bin the lap budget removed between the save planes. Between two planes a bin's spectrum ``S`` obeys ``dS/dz = G - alpha S``, with ``alpha = 2 gamma_omega`` the spectral absorber's power rate and ``G`` whatever else feeds or drains the bin (the nonlinear generation, the transverse ramp). Taking ``G`` constant across the interval, the two planes' values fix it, and the absorber removed ``G dz - (S1 - S0)``: exact for a bin that only decays, and for one fed at a steady rate. A trapezoid of ``alpha S`` is not: light the absorber takes in a fraction of a micrometre, such as the input's own share of an absorbed bin, would be overcounted by about ``alpha dz / 2``. The lap budget's part is its share ``gamma_lap / gamma_omega`` of the bin's loss; a negative interval (a bin drained faster than its absorber explains) counts zero. Parameters ---------- beam : numpy.ndarray The whole beam's spectrum at each plane, ``(n_z, nt)`` (``i_omega_beam``). z : numpy.ndarray The planes, m, increasing. gamma_omega, gamma_lap : numpy.ndarray The spectral absorber's amplitude rate and the lap budget's share, 1/m. Returns ------- numpy.ndarray The removed energy per bin, ``(nt,)``, in the units of ``beam``. Examples -------- >>> import numpy as np >>> z = np.array([0.0, 1e-6]) >>> rate = np.array([1e6]) >>> beam = np.array([[1.0], [np.exp(-2.0)]]) # decaying at 2 x 1e6 /m, no source >>> lap_lost(beam, z, rate, rate).round(12).tolist() [0.864664716763] """ alpha = 2.0 * gamma_omega share = np.divide( gamma_lap, gamma_omega, out=np.zeros_like(gamma_lap), where=gamma_omega > 0.0 ) lost = np.zeros(beam.shape[1]) acting = alpha > 0.0 for i in range(len(z) - 1): dz = float(z[i + 1] - z[i]) s0, s1 = beam[i], beam[i + 1] x = np.where(acting, alpha * dz, 1.0) # The constant source the two planes imply, by the exact interval solution # S1 = S0 exp(-x) + (G / alpha) (1 - exp(-x)). source = alpha * (s1 - s0 * np.exp(-x)) / -np.expm1(-x) removed = np.where(acting, source * dz - (s1 - s0), 0.0) lost += share * np.maximum(removed, 0.0) return lost
[docs] def lap_loss_share( lost: Float[np.ndarray, "*delays n_omega"], kept: Float[np.ndarray, "*delays n_omega"], omega: Float[np.ndarray, " n_omega"], band: tuple[float, float], ) -> Float[np.ndarray, "*delays"]: """Return the share of a band's energy that the lap budget removed. ``lost / (lost + kept)`` summed over the band's bins, with ``lost`` the energy per bin the lap budget removed over the slab (``lap_lost`` of :func:`pnps.simulate.run_delay_point`) and ``kept`` the whole beam's spectrum at the exit (``i_omega_beam`` at the last plane), both in the same units. Parameters ---------- lost, kept : numpy.ndarray Spectra over the frequency axis, with any leading delay axes. omega : numpy.ndarray The absolute angular frequency of each bin, rad/s. band : tuple of float The band's wavelength limits, m, in either order. Returns ------- numpy.ndarray The share in ``[0, 1]``, of the leading shape; NaN where the band holds no energy. Examples -------- >>> import numpy as np >>> from scipy.constants import c >>> omega = 2 * np.pi * c / np.array([150e-9, 200e-9, 300e-9]) >>> lap_loss_share(np.array([1.0, 0.0, 0.0]), np.array([3.0, 4.0, 4.0]), omega, ... (140e-9, 210e-9)).round(3).item() 0.125 """ lam = 2 * np.pi * c / np.where(omega > 0.0, omega, np.nan) inside = (lam >= min(band)) & (lam <= max(band)) removed = np.sum(np.where(inside, lost, 0.0), axis=-1) total = removed + np.sum(np.where(inside, kept, 0.0), axis=-1) with np.errstate(invalid="ignore", divide="ignore"): return np.where(total > 0.0, removed / total, np.nan)
def _in_band(tgrid: TimeGrid) -> Bool[np.ndarray, " n_omega"]: """Return the bins of the requested band, ``omega_min <= omega <= omega_max``. Parameters ---------- tgrid : TimeGrid The temporal grid. Returns ------- numpy.ndarray The mask, ``(nt,)``. """ return (tgrid.omega >= tgrid.omega_min) & (tgrid.omega <= tgrid.omega_max)
[docs] def transverse_rate( kx: Float[np.ndarray, " n_x"], strength: float, fraction: float = 0.1 ) -> Float[np.ndarray, "n_y n_x"]: """Return the transverse-wavevector safety ramp's power rate on the grid. With ``rho = max(|k_x| / max|k_x|, |k_y| / max|k_y|)`` the rate is ``strength P(rho)``, ``P`` zero up to ``rho = 1 - fraction`` and rising as a raised cosine to one at the grid's largest wavenumber: solprop's safety ramp (its SEP 40), re-derived here for the reference model, with the strength :func:`transverse_strength` gives. It damps content that reaches the outer band of a grid too small for its products; on a grid sized by :func:`pnps.grids.optimal_spatial_grid` it does no measurable work. Parameters ---------- kx : numpy.ndarray The stored momentum axis (the same on both axes), rad/m. strength : float The power rate at the grid's edge, 1/m; 0 for none. fraction : float, optional The ramp's width as a fraction of the largest wavenumber, in (0, 1). Returns ------- numpy.ndarray The power rate, ``(n_y, n_x)``, 1/m; a field decays by ``exp(-rate z / 2)``. """ rho = np.abs(kx) / np.max(np.abs(kx)) inside = np.clip((rho - 1 + fraction) / fraction, 0.0, 1.0) ramp = 0.5 * (1 - np.cos(np.pi * inside)) return strength * np.maximum(ramp[:, None], ramp[None, :])
[docs] def transverse_strength(tgrid: TimeGrid, sgrid: SpaceGrid, fraction: float) -> float: """Return the safety ramp's peak power rate, as solprop designs it. solprop does not take the ramp's strength from the caller: it designs it so that content in the ramp's upper half is attenuated by ``Gamma_min + 2`` nepers (``log(5e3) + 2``, about 10.5) over the grid's half-width, the distance in which it would cross the grid and come back (:func:`solprop.spatial_absorber.safety_ramp_strength`). This evaluates that rule on this package's own grids and index: the medium's wavenumbers ``Re n(omega) omega / c`` over the requested band ``[omega_min, omega_max]``, and the ramp's midpoint ``(1 - fraction / 2)`` of the largest ``|k_x|``. Parameters ---------- tgrid : TimeGrid The temporal grid, for the requested band. sgrid : SpaceGrid The transverse grid, for its momentum axis and half-width. fraction : float The ramp's width as a fraction of the largest wavenumber, in (0, 1). Returns ------- float The ramp's power rate at the grid's edge, 1/m. """ omega = tgrid.omega band = (omega >= tgrid.omega_min) & (omega <= tgrid.omega_max) k = np.real(silica_index(omega[band])) * omega[band] / c top = float(np.max(np.abs(sgrid.kx))) half_width = sgrid.delta_x * sgrid.kx.size / 2 return safety_ramp_strength((1 - fraction / 2) * top, k, half_width)