# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""The run configuration and everything built from it once, before any delay point.
:class:`Config` describes the instrument and the run; :func:`build_setup` turns it into
a :class:`Setup`: the grids, the beamlets and their chromatic masks, the formed-input
machinery, the resolved collection windows and the absorber rates. A setup holds no
engine state; :mod:`pnps.bridge` puts one on solprop, and :mod:`pnps.simulate` runs
delay points through it.
"""
import logging
import math
import warnings
from dataclasses import dataclass, replace
from typing import Literal
import numpy as np
from jaxtyping import Complex, Float
from pnps.absorber import lap_free_band, required_trange, spectral_absorber
from pnps.beams import (
Beam,
Beamlets,
rcos_edge_default,
tanh_apod_default,
)
from pnps.exceptions import ConfigError, WindowOverlapWarning
from pnps.extraction import WindowSpec
from pnps.form_input import (
InputFormer,
beamlet_diagnostics,
build_input_former,
)
from pnps.geometry import (
Geometry,
SignalRegion,
check_geometry,
input_layout,
signal_region,
)
from pnps.grids import SpaceGrid, TimeGrid, space_grid, time_grid
from pnps.input_pulse import InputPulse, injected_spectrum
from pnps.kernels import size_thread_pool
from pnps.materials import (
chi3_sio2,
silica_k2,
silica_n2,
silica_raman_fraction,
)
from pnps.pulse import gaussian_pulse_spectrum, planck_taper
__all__ = [
"Config",
"Setup",
"build_setup",
"rescale_delivered_energy",
]
logger = logging.getLogger(__name__)
[docs]
@dataclass(frozen=True)
class Config:
"""Complete description of one TG-FROG (or self-diffraction FROG) simulation.
Attributes
----------
lam0 : float
Carrier wavelength in m.
tau_fwhm : float
Intensity FWHM of the transform-limited input pulse in s. With
``input_pulse`` set it is nominal metadata only — the injected field
defines the duration — and is recorded unchanged so a declared
instrument keeps its identity.
energy : float
Pre-mask pulse energy (all the arms together) in J: the beam's axial flux in
air before the mask.
thickness : float
Slab thickness in m.
mask_diam, mask_spacing : float
Input-mask hole diameter and edge-to-edge spacing in m.
beam : HE11Beam, GaussianBeam or UniformBeam
Input beam geometry (UniformBeam is the ideal-instrument control).
windows : tuple of WindowSpec
Collection apertures (a series of hole diameters in the examples), centred
where the layout's signal appears (:func:`pnps.geometry.signal_centre`).
lam_lims : tuple of float
Wavelength limits of the simulation window in m.
trange : float
Requested time-window extent in s. There is no temporal apodisation:
walked-off light is carried exactly on the periodic window, and only
frequencies that would wrap a full period back onto the pulse are
absorbed (the lap budget, see
:func:`pnps.absorber.spectral_absorber`). A larger window
keeps more of the extreme-DUV spectrum.
r_max : float
Transverse containment radius in m.
n_transverse : int
Transverse samples per axis (even).
material : str
Only ``"SiO2"`` is supported.
geometry : {"tg", "sd"}
The beam layout (:mod:`pnps.geometry`): ``"tg"`` (the default) is the
four-hole transient-grating boxcar, three inputs with the signal in the fourth
corner; ``"sd"`` is self-diffraction, two holes on the x axis with the signal
``2 k_E - k_G`` one slot further out on the probe's side. It sets the input
holes and the signal region ``i_omega_full`` sums; place the windows at
:func:`pnps.geometry.signal_centre`. solprop's statistics express both signal
regions (the SD one as a half-plane of the mask,
:func:`pnps.geometry.signal_half_plane`).
apod : str
Input-hole edge profile, see :func:`pnps.beams.chromatic_mask`. The
default, ``"area"``, is the instrument's exact hard aperture, each momentum
pixel weighted by the fraction of it inside the hole (supersampled
``apod_param`` times per axis, only where the hole edge crosses the pixel).
apod_param : float
Input-hole edge parameter: the supersampling factor for ``"area"`` (default
4), the supergaussian order, or an edge width in m.
gdd, tod : float
Input chirp: group-delay dispersion (s^2), third-order dispersion
(s^3). Must both be zero when ``input_pulse`` is set: the injected
field carries its own phase.
input_pulse : InputPulse or None
A stored complex spectrum to use as the source field instead of the
synthetic Gaussian, prepared as described in
:mod:`pnps.input_pulse`. The illumination profile and the chromatic
input holes are real amplitude factors on one 1-D reference
spectrum, so an arbitrary field composes exactly; everything
downstream — vignetting, the recorded beamlet truth, the propagation
— is unchanged.
raman : bool
Include the delayed Raman response of fused silica (off by default): the
Hollenbeck and Cantrell shape of optmat's silica nonlinear bundle, carrying
the bundle's fraction f_R of chi3 while the instantaneous Kerr response keeps
``1 - f_R`` (:func:`pnps.materials.silica_raman_fraction`). Off, the whole
Kerr index is instantaneous.
fftsize : str
Temporal sample-count rounding, ``"smooth"`` or ``"pow2"``.
gamma_max : float
Peak amplitude rate of the spectral edge absorber in 1/m.
transverse_absorber : bool
Whether the transverse-wavevector safety ramp is on (solprop's safety ramp,
its :class:`~solprop.boundaries.SpatialAbsorber` without a real-space
collar; :func:`pnps.absorber.transverse_rate`). Its strength is solprop's
design, not a setting: content in the ramp's upper half loses about 10.5
nepers over the grid's half-width (:func:`pnps.absorber.transverse_strength`).
It damps content that reaches the outer band of a grid too small for the
mixing products, keeping it from folding back; on a grid sized by
:func:`pnps.grids.optimal_spatial_grid` it does no measurable work.
transverse_fraction : float
The ramp's width as a fraction of the largest wavenumber, in (0, 1).
time_headroom : float
Protected half-width around t = 0 holding the pulse and the delay
scan, in s. Frequencies whose group-delay walk-off over the slab
exceeds the lap budget (window length minus twice this) are absorbed
(see :func:`pnps.absorber.spectral_absorber`). Delays within 75% of it
are always admitted; a longer one is admitted when light that wraps the
window cannot act at it (:func:`pnps.absorber.wrap_coupling`).
absorption : bool
Keep the material loss of optmat's index, its imaginary part (off by
default: the slab is lossless, with optmat's real index unchanged). Silica
absorbs strongly below about 160 nm (5e6 /m at 131 nm); with it on, certify
the step on this model, since the interaction-picture march is
pre-asymptotic in those bins until ``h << 1/alpha``.
node_budget : int
solprop's memory budget per transform chunk, in bytes (see solprop's
resource guide); larger chunks are faster and hold more memory.
edge_diagnostic : bool
Compute the time-window edge fraction at every save position (one
blocked inverse transform along omega per plane). Off by default, when
``edge_fraction`` is reported as NaN.
transverse_monitor : bool
Watch the transverse grid's edge in real space with solprop's boundary
monitor (:data:`pnps.bridge.BOUNDARY_CHECK`): a launch or a field that puts
more than 1e-6 of its energy in the outer 5 % of the grid warns, and more
than 1e-4 stops the run, since that light would wrap round the periodic grid.
On by default; off only for a grid known to be too small, such as the test
suite's.
stepper : {'dopri5', 'rk4ip'}
solprop's march: ``'dopri5'`` replays the fifth-order Runge-Kutta pair on
the fixed schedule (fifteen field volumes, the most accurate per step);
``'rk4ip'`` is solprop's low-storage interaction-picture RK4, this
package's own stencil, in four field volumes.
reduction : {'auto', 'host', 'solprop'}
Where each save plane is reduced to the observables: ``'host'`` copies the
field out of solprop and reduces it here (:mod:`pnps.reduce_numba`);
``'solprop'`` keeps no field and reads solprop's far-field statistics
(:mod:`pnps.statistics`), which every in-tree solprop backend forms
(``numpy_ref`` and ``native``), and needs windows solprop
can express. The two agree to rounding and cost the same on a CPU; the
solprop path saves the field copy, a field volume per plane, which is the
expensive part on a device. ``'auto'`` (the default) takes ``'solprop'``
whenever solprop accepts the windows without a warning
(:func:`pnps.statistics.statistics_unavailable`) and ``'host'`` otherwise.
exact_windows : bool
Collect the windowed spectra (``i_omega_win``, ``i_omega_reimaged``) through
each window's exact hard disc instead of its rendering on the momentum grid,
which misses the hard disc by up to a few 1e-3 of the trace's peak for
windows spanning a few bins (``docs/windows.md``). The exact disc applies to
the nonlinear part of each plane, the field less the input carried by the
linear flow, whose support is compact. With the solprop reduction (what
``'auto'`` resolves to) solprop forms both on its backend (its ``exact``
aperture profile on the ``nonlinear`` field, SEP 53): no field leaves the
device, and the masks are built there once. With ``'host'`` this package
does it (:class:`pnps.exact_windows.ExactWindows`): it holds the input
state for the subtraction and one mask per window and band frequency,
``n_windows * n_band * n^2`` doubles. The window's rendering (``apod``,
``weighting``) then plays no part. Off by default.
"""
lam0: float
tau_fwhm: float
energy: float
thickness: float
mask_diam: float
mask_spacing: float
beam: Beam
windows: tuple[WindowSpec, ...]
lam_lims: tuple[float, float]
trange: float
r_max: float
n_transverse: int
material: str = "SiO2"
geometry: Geometry = "tg"
input_pulse: InputPulse | None = None
apod: str = "area"
apod_param: float = 4.0
gdd: float = 0.0
tod: float = 0.0
raman: bool = False
fftsize: str = "smooth"
gamma_max: float = 5e6
transverse_absorber: bool = True
transverse_fraction: float = 0.1
time_headroom: float = 40e-15
absorption: bool = False
node_budget: int = 1 << 30
edge_diagnostic: bool = False
transverse_monitor: bool = True
stepper: Literal["dopri5", "rk4ip"] = "rk4ip"
reduction: Literal["auto", "host", "solprop"] = "auto"
exact_windows: bool = False
[docs]
@dataclass(frozen=True)
class Setup:
"""Everything precomputed once per configuration; nothing field-sized.
Built by :func:`build_setup`. The input state is formed on the fly for each
delay (:func:`~pnps.simulate.delayed_input`), so the setup holds only separable
tables: it can be built at production grid sizes on any machine.
Attributes
----------
cfg : Config
The configuration.
tgrid, sgrid : TimeGrid, SpaceGrid
The simulation grids.
windows : tuple of WindowSpec
Collection apertures with their edge parameters resolved.
e_omega_input : numpy.ndarray
The band-limited 1-D input spectrum, ``(nt,)``.
former : InputFormer
The tables the input state is formed from.
beamlets : Beamlets
The beamlet spectra and delivered energy recorded in scan files.
gamma_omega : numpy.ndarray
The spectral absorber's amplitude rate, ``(nt,)``, 1/m.
gamma_lap : numpy.ndarray
The lap budget's share of it, ``(nt,)``, 1/m
(:class:`pnps.absorber.SpectralRates`).
gd_band : numpy.ndarray
Indicator of the bins the lap budget absorbs, ``(nt,)``.
chi3 : float
Fused-silica chi3 in m^2/V^2 (:func:`pnps.materials.chi3_sio2`), the total:
a Raman run gives ``1 - raman_fraction`` of it to the instantaneous response.
n2 : float
The total Kerr index behind it, m^2/W.
n2_extrapolated : bool
Whether n2 is the optmat fit evaluated outside its validated range.
raman_fraction : float
The Raman fraction f_R of the delayed response, 0.0 when ``cfg.raman`` is
off.
signal_region : SignalRegion
The momentum region ``i_omega_full`` sums
(:func:`pnps.geometry.signal_region`).
"""
cfg: Config
tgrid: TimeGrid
sgrid: SpaceGrid
windows: tuple[WindowSpec, ...]
e_omega_input: Complex[np.ndarray, " n_omega"]
former: InputFormer
beamlets: Beamlets
gamma_omega: Float[np.ndarray, " n_omega"]
gamma_lap: Float[np.ndarray, " n_omega"]
gd_band: Float[np.ndarray, " n_omega"]
chi3: float
n2: float
n2_extrapolated: bool
raman_fraction: float
signal_region: SignalRegion
# Conventional edge parameter per profile, for a WindowSpec that leaves it unset. The
# tanh width is three mask-plane pixels; the raised-cosine half-width of two pixels is
# the collection-window recommendation, wide enough to sample smoothly and narrow enough
# that its compact support clears the input arms across the band. "area" takes a
# supersampling factor rather than a width.
_DEFAULT_EDGE_PARAM = {
"tanh": tanh_apod_default,
"rcos": rcos_edge_default,
"hard": lambda _tgrid, _sgrid, _zmask: 0.0,
"area": lambda _tgrid, _sgrid, _zmask: 4.0,
}
def _resolve_window(
window: WindowSpec, tgrid: TimeGrid, sgrid: SpaceGrid
) -> WindowSpec:
"""Fill in a window's conventional edge parameter if it was left unset.
Parameters
----------
window : WindowSpec
The collection aperture as configured.
tgrid : TimeGrid
The temporal grid.
sgrid : SpaceGrid
The transverse grid.
Returns
-------
WindowSpec
``window`` itself when ``apod_param`` is set, otherwise a copy with the
profile's conventional edge parameter filled in.
Raises
------
ConfigError
If the profile has no conventional edge parameter.
"""
if window.apod_param is not None:
return window
if window.apod not in _DEFAULT_EDGE_PARAM:
raise ConfigError(
f"no conventional apod_param for apod={window.apod!r}; set it explicitly"
)
default = _DEFAULT_EDGE_PARAM[window.apod](tgrid, sgrid, window.zmask)
return replace(window, apod_param=default)
[docs]
def build_setup(cfg: Config) -> Setup:
"""Build grids, input tables, absorber and resolved windows.
Parameters
----------
cfg : Config
The configuration.
Returns
-------
Setup
The grids, input tables, absorber and resolved windows of ``cfg``.
Raises
------
ConfigError
For an unsupported material or layout, an empty window list, an
injected input pulse combined with a configured chirp, or an input spectrum
the window cannot carry.
"""
if cfg.material != "SiO2":
raise ConfigError(f"only SiO2 is supported, got {cfg.material!r}")
check_geometry(cfg.geometry)
if not cfg.windows:
raise ConfigError("at least one collection window is required")
if cfg.input_pulse is not None and (cfg.gdd != 0.0 or cfg.tod != 0.0):
raise ConfigError(
f"input_pulse carries its own spectral phase, but Config also "
f"requests gdd={cfg.gdd!r}, tod={cfg.tod!r}; apply the chirp to "
"the injected field instead of the configuration"
)
size_thread_pool() # the former is a numba kernel
tgrid = time_grid(cfg.lam0, cfg.lam_lims, cfg.trange, cfg.fftsize)
sgrid = space_grid(cfg.r_max, cfg.n_transverse)
rates = spectral_absorber(
tgrid,
cfg.thickness,
gamma_max=cfg.gamma_max,
time_headroom=cfg.time_headroom,
)
_warn_lap_budget_in_band(cfg, tgrid, rates.gamma_lap)
n2, n2_extrapolated = silica_n2(cfg.lam0)
windows = tuple(_resolve_window(w, tgrid, sgrid) for w in cfg.windows)
if cfg.exact_windows:
_warn_windows_on_input_holes(cfg)
e_omega = (
gaussian_pulse_spectrum(tgrid, cfg.tau_fwhm, gdd=cfg.gdd, tod=cfg.tod)
if cfg.input_pulse is None
else injected_spectrum(tgrid, cfg.input_pulse)
)
# Band-limit the INPUT once, smoothly, over the same edge regions the
# spectral absorber guards: the source of the instrument model has finite
# band by definition, and the C-infinity rolloff keeps the hard
# grid-boundary truncation of the pulse's spectral tails from ringing into
# the time-window edges. This is part of the input definition, not an
# in-loop window — step-size convergence is untouched. An injected field gets
# exactly the same treatment: whatever it carries outside the simulation band
# would be absorbed within a micrometre of the entrance anyway, so tapering
# it here is what keeps the recorded truth equal to the field that actually
# propagates. The taper vanishes outside solprop's active band (the same
# omega_min/2 < omega < 1.1 omega_max), so solprop's hard band limit never
# touches the input.
e_omega = e_omega * planck_taper(
tgrid.omega,
tgrid.omega_min / 2,
tgrid.omega_min,
tgrid.omega_max,
1.1 * tgrid.omega_max,
)
if not np.any(e_omega):
raise ConfigError(
"the input spectrum is identically zero after the band-limit: the "
f"source's band lies outside the simulation window {cfg.lam_lims} "
"(widen lam_lims, or check the injected field's support)"
)
former = build_input_former(
tgrid,
sgrid,
cfg.beam,
e_omega,
cfg.energy,
cfg.mask_diam,
cfg.mask_spacing,
cfg.apod,
cfg.apod_param,
cfg.geometry,
k2=silica_k2(tgrid, absorption=cfg.absorption),
)
return Setup(
cfg=cfg,
tgrid=tgrid,
sgrid=sgrid,
windows=windows,
e_omega_input=e_omega,
former=former,
beamlets=beamlet_diagnostics(former, tgrid, sgrid),
gamma_omega=rates.gamma_omega,
gamma_lap=rates.gamma_lap,
gd_band=rates.gd_band,
chi3=chi3_sio2(cfg.lam0),
n2=n2,
n2_extrapolated=n2_extrapolated,
raman_fraction=silica_raman_fraction() if cfg.raman else 0.0,
signal_region=signal_region(
cfg.geometry, tgrid.omega, cfg.beam.f_foc, cfg.mask_diam, cfg.mask_spacing
),
)
def _warn_windows_on_input_holes(cfg: Config) -> None:
"""Warn for each exact window that overlaps the far field of an input hole.
An input hole at mask-plane position ``h`` before the focusing lens sends its arm
along the angle ``h / f_foc``, which a window at distance ``zmask`` sees at
``h * zmask / f_foc``, a disc of diameter ``mask_diam * zmask / f_foc``. Exact
windows collect only the nonlinear part of the field, so where a window covers an
arm the transmitted input light a detector would see is left out.
Parameters
----------
cfg : Config
The configuration, with ``exact_windows`` set.
"""
layout = input_layout(cfg.geometry, cfg.mask_diam, cfg.mask_spacing)
arms = layout.holes[layout.weights > 0.0]
for j, w in enumerate(cfg.windows):
scale = w.zmask / cfg.beam.f_foc
gaps = [
math.hypot(w.holex - hx * scale, w.holey - hy * scale)
- (w.holediam + cfg.mask_diam * scale) / 2
for hx, hy in arms
]
if min(gaps) < 0.0:
warnings.warn(
f"window {j + 1} overlaps an input hole's far field by "
f"{-min(gaps) * 1e3:.3g} mm; with exact_windows it collects only the "
"nonlinear field, so the transmitted input light a detector there "
"would see is left out of its spectra",
WindowOverlapWarning,
stacklevel=3,
)
def _warn_lap_budget_in_band(
cfg: Config, tgrid: TimeGrid, gamma_lap: Float[np.ndarray, " n_omega"]
) -> None:
"""Log a warning when the lap budget absorbs inside the requested band.
Light the lap budget absorbs never reaches the spectrometer, so a window too
short for the band's walk-off loses signal there. The run's ``lap_lost`` says how
much; this says, before any run, where and how long a window would avoid it.
Parameters
----------
cfg : Config
The configuration.
tgrid : TimeGrid
Its temporal grid.
gamma_lap : numpy.ndarray
The lap budget's rate, ``(nt,)``.
"""
lam_short, lam_long = lap_free_band(tgrid, gamma_lap)
lam_min, lam_max = min(cfg.lam_lims), max(cfg.lam_lims)
band = (tgrid.omega >= tgrid.omega_min) & (tgrid.omega <= tgrid.omega_max)
if not np.any(band & (gamma_lap > 0.0)):
return
needed = required_trange(tgrid, cfg.thickness, cfg.time_headroom)
logger.warning(
"the lap budget absorbs inside the requested band %.4g-%.4g nm: only "
"%.4g-%.4g nm is untouched, so light walking off further is lost before "
"the spectrometer (the run's lap_lost says how much). A trange of at least "
"%.4g fs keeps the whole band (it is %.4g fs).",
lam_min * 1e9,
lam_max * 1e9,
lam_short * 1e9,
lam_long * 1e9,
needed * 1e15,
cfg.trange * 1e15,
)
[docs]
def rescale_delivered_energy(setup: Setup, energy: float) -> Setup:
"""Return the setup with its input rescaled to a stated delivered energy.
``Config.energy`` is the *pre-mask* energy; what the slab receives is what
the holes pass, which depends on the beam model and the grid. A control run
that must deliver the same post-hole energy as a reference (the ideal
uniform-illumination instrument, say) rescales the input instead: the
amplitude scale of the former and the recorded beamlet diagnostics change
together, nothing else does.
Parameters
----------
setup : Setup
The configuration.
energy : float
Post-hole energy of all the arms to deliver, J, positive.
Returns
-------
Setup
A new setup delivering ``energy``.
Raises
------
ConfigError
If ``energy`` is not positive and finite.
"""
if not (np.isfinite(energy) and energy > 0):
raise ConfigError(f"energy must be positive and finite, got {energy!r}")
scale = float(np.sqrt(energy / setup.beamlets.delivered_energy))
beamlets = setup.beamlets
return replace(
setup,
former=replace(setup.former, scale=setup.former.scale * scale),
# _replace is the NamedTuple update API; naming every field would
# silently drop any diagnostic added to Beamlets later.
beamlets=beamlets._replace(
i_omega_beamlet=beamlets.i_omega_beamlet * scale**2,
i_omega_beamlet_reimaged=beamlets.i_omega_beamlet_reimaged * scale**2,
delivered_energy=beamlets.delivered_energy * scale**2,
),
)