# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Time/frequency and transverse grids for envelope propagation.
The temporal grid is the analytic-envelope grid: a complex field sampled on a
centred time axis ``t = (n - N/2) * delta_t``, whose discrete Fourier dual is
the *absolute* angular frequency axis ``omega = omega0 + 2*pi*fftfreq(N,
delta_t)`` — FFT-ordered, not monotonic. The sample spacing is fixed by the
requested wavelength window (Nyquist for the envelope bandwidth), and the
sample count by the requested time window, rounded up to an efficient FFT
size.
The transverse grid is a square, centred real-space axis ``x = (n - N/2) *
delta_x`` with FFT-ordered momentum axis ``kx = 2*pi*fftfreq(N, delta_x)``.
Both x and y use the same axis. The physical half-width of the grid is ``r_max * (1 +
window_factor)``: the caller-facing ``r_max`` is the radius meant to contain
the field, and the extra margin is grid headroom.
"""
from dataclasses import dataclass
import numpy as np
from jaxtyping import Bool, Float
from scipy.constants import c
from pnps.exceptions import GridError
from pnps.geometry import check_geometry
__all__ = [
"SpaceGrid",
"TimeGrid",
"fft_size",
"optimal_spatial_grid",
"space_grid",
"time_grid",
]
[docs]
def fft_size(needed: float, mode: str = "smooth") -> int:
"""Round a required sample count up to an efficient FFT size.
Parameters
----------
needed : float
Minimum number of samples required.
mode : str
``"smooth"`` for the next even 2,3,5-smooth integer (tracks the
requirement closely), ``"pow2"`` for the next power of two. Evenness
is required by the centred grid layout ``t = (n - N/2) * delta_t``.
Returns
-------
int
The rounded-up transform size.
Raises
------
GridError
If ``mode`` is not ``"smooth"`` or ``"pow2"``.
"""
n = int(np.ceil(needed))
if mode == "pow2":
return 1 << max(0, (n - 1)).bit_length()
if mode == "smooth":
m = n
while True:
k = m
for p in (2, 3, 5):
while k % p == 0:
k //= p
if k == 1 and m % 2 == 0:
return m
m += 1
raise GridError(f"fft size mode must be 'smooth' or 'pow2', got {mode!r}")
[docs]
@dataclass(frozen=True)
class TimeGrid:
"""Temporal/spectral grid for the analytic envelope.
Attributes
----------
lam0 : float
Reference (carrier) wavelength in m.
omega0 : float
Carrier angular frequency ``2*pi*c/lam0`` in rad/s.
delta_t : float
Time sample spacing in s.
t : numpy.ndarray
Centred time axis, shape ``(nt,)``, in s.
omega : numpy.ndarray
Absolute angular frequency axis in rad/s, FFT-ordered (element 0 is
the carrier), shape ``(nt,)``.
sidx : numpy.ndarray
Boolean mask of "real" frequencies for which the dispersion relation
is evaluated: ``omega_min/2 < omega < 1.1*omega_max``.
omega_min, omega_max : float
Angular-frequency limits of the physical band, ``2*pi*c/lam`` at the
long/short wavelength limits.
"""
lam0: float
omega0: float
delta_t: float
t: Float[np.ndarray, " n_t"]
omega: Float[np.ndarray, " n_omega"]
sidx: Bool[np.ndarray, " n_omega"]
omega_min: float
omega_max: float
[docs]
@property
def nt(self) -> int:
"""Number of temporal samples.
Returns
-------
int
``n_t``, equal to ``n_omega``.
"""
return len(self.t)
[docs]
def time_grid(
lam0: float,
lam_lims: tuple[float, float],
trange: float,
fftsize: str = "smooth",
) -> TimeGrid:
"""Build the envelope time/frequency grid.
The sample spacing is the envelope Nyquist limit for the requested
wavelength window (extended 10% on the blue side, headroom for the
absorbing edge), and the sample count is ``trange / delta_t`` rounded up
to an FFT size. The realised time window is therefore >= ``trange``.
Parameters
----------
lam0 : float
Carrier wavelength in m.
lam_lims : tuple of float
(min, max) wavelength limits of the simulation window in m.
trange : float
Requested extent of the time window in s.
fftsize : str
Sample-count rounding mode, see :func:`fft_size`.
Returns
-------
TimeGrid
The envelope grid, with ``n_t`` samples.
Raises
------
GridError
If the wavelength limits do not bracket ``lam0``.
"""
lam_min, lam_max = min(lam_lims), max(lam_lims)
if not lam_min < lam0 < lam_max:
raise GridError(f"lam0 {lam0} not inside lam_lims {lam_lims}")
f_min = c / lam_max
f_max = c / lam_min
f_max_win = 1.1 * f_max # blue-side headroom for the absorbing edge
f0 = c / lam0
omega0 = 2 * np.pi * f0
# Envelope Nyquist: the largest |relative frequency| the grid must hold.
delta_t = 1.0 / (2.0 * max(f_max_win - f0, f0 - f_min))
nt = fft_size(trange / delta_t, fftsize)
t = (np.arange(nt) - nt / 2) * delta_t
omega = omega0 + 2 * np.pi * np.fft.fftfreq(nt, delta_t)
omega_min = 2 * np.pi * f_min
omega_max = 2 * np.pi * f_max
sidx = (omega > omega_min / 2) & (omega < 2 * np.pi * f_max_win)
return TimeGrid(
lam0=lam0,
omega0=omega0,
delta_t=delta_t,
t=t,
omega=omega,
sidx=sidx,
omega_min=omega_min,
omega_max=omega_max,
)
[docs]
@dataclass(frozen=True)
class SpaceGrid:
"""Square transverse grid (same axis for x and y).
Attributes
----------
r_max : float
Caller-facing containment radius in m (the physical half-width is
``r_max * (1 + window_factor)``).
delta_x : float
Real-space sample spacing in m.
x : numpy.ndarray
Centred real-space axis, shape ``(n,)``, in m. Used for both x and y.
kx : numpy.ndarray
FFT-ordered transverse momentum axis, shape ``(n,)``, in rad/m. Used
for both kx and ky.
"""
r_max: float
delta_x: float
x: Float[np.ndarray, " n_x"]
kx: Float[np.ndarray, " n_x"]
[docs]
@property
def n(self) -> int:
"""Number of samples along each transverse axis.
Returns
-------
int
``n``, equal to ``n_y`` and ``n_x``.
"""
return len(self.x)
[docs]
@property
def k_nyquist(self) -> float:
"""Transverse Nyquist momentum ``pi / delta_x`` in rad/m.
Returns
-------
float
The Nyquist momentum in rad/m.
"""
return np.pi / self.delta_x
[docs]
def space_grid(r_max: float, n: int, window_factor: float = 0.1) -> SpaceGrid:
"""Build the square transverse grid.
Parameters
----------
r_max : float
Containment radius in m; the grid half-width is
``r_max * (1 + window_factor)``.
n : int
Samples per axis; must be even (centred layout and the re-imaging
identity in the extraction both require it).
window_factor : float
Fractional half-width margin beyond ``r_max`` (inherited convention).
Returns
-------
SpaceGrid
The ``n`` by ``n`` transverse grid.
Raises
------
GridError
If ``n`` is odd.
"""
if n % 2 != 0:
raise GridError(f"transverse sample count must be even, got {n}")
half_width = r_max * (1 + window_factor)
delta_x = 2 * half_width / n
x = (np.arange(n) - n / 2) * delta_x
kx = 2 * np.pi * np.fft.fftfreq(n, delta_x)
return SpaceGrid(r_max=r_max, delta_x=delta_x, x=x, kx=kx)
[docs]
def optimal_spatial_grid( # noqa: PLR0913, PLR0917 - the instrument's lengths, one each
f_foc: float,
mask_diam: float,
mask_spacing: float,
lam_min: float,
lam_max: float,
n_airy: int = 5,
pts_per_lobe: int = 10,
safety: float = 1.5,
margin: float = 1.1,
geometry: str = "tg",
) -> tuple[float, int]:
"""Size the transverse grid for a beam layout.
Real-space containment requires ``n_airy`` Airy radii of the largest-hole
focal spot at the longest wavelength; resolution requires
``pts_per_lobe`` samples per Airy lobe at the shortest; and the momentum
span must hold the third-order mixing products with ``safety`` headroom. The
returned sample count is the next even 2,3,5-smooth size above ``margin`` times
the strictest requirement.
The mixing bound follows the layout (:mod:`pnps.geometry`). In the TG boxcar the
outermost hole edge is ``mask_spacing/2 + mask_diam`` from the axis and the chi3
products are bounded by three times that. In self-diffraction the signal itself
is the outermost thing, at ``3s/2`` (``s = mask_spacing + mask_diam``), so its
edge, ``3s/2 + mask_diam/2``, is the bound, with no further factor.
Parameters
----------
f_foc : float
Focusing focal length in m.
mask_diam, mask_spacing : float
Hole diameter and edge-to-edge hole spacing in m.
lam_min, lam_max : float
Wavelength limits of the simulation window in m.
n_airy : int
Airy radii of real-space containment, see above.
pts_per_lobe : int
Samples per Airy lobe at the shortest wavelength.
safety : float
Headroom factor on the momentum span of the mixing products.
margin : float
Factor applied to the strictest sample-count requirement.
geometry : {"tg", "sd"}, optional
The beam layout.
Returns
-------
tuple of (float, int)
``(r_max, n)`` for :func:`space_grid`.
Raises
------
ConfigError
For an unknown layout.
"""
check_geometry(geometry)
if geometry == "sd":
# The signal's outer edge, quoted directly: no factor of three below.
x_max, reach = 1.5 * (mask_spacing + mask_diam) + mask_diam / 2, 1
else:
# The outermost hole edge; chi3 products reach three times it.
x_max, reach = mask_spacing / 2 + mask_diam, 3
r_airy_max = 1.22 * lam_max * f_foc / mask_diam
r_airy_min = 1.22 * lam_min * f_foc / mask_diam
r_max = n_airy * r_airy_max
dx_max = r_airy_min / pts_per_lobe
n_real = 2 * r_max / dx_max
k_nl_max = safety * reach * 2 * np.pi * x_max / (lam_min * f_foc)
n_kspace = 2 * r_max * k_nl_max / np.pi
n = fft_size(margin * max(n_real, n_kspace), "smooth")
return r_max, n